ウェブサイト検索

reactjs - Preact/Typescript/Enzyme: 型 'Component' にプロパティ 'refs' が存在しません


私は、Preact、TypeScript、Parcel を使用したプロジェクトのために Jest を設定しています。コンポーネントコード自体ではすべて正常に動作しますが、Jest テストを設定し、Enzyme の mount または shallow 関数(preact アダプターを使用)でコンポーネントをレンダリングすると、関数に渡されている型に ref 属性が欠けていることを示すエラーが発生します:

src/features/homepage/homepage.spec.tsx:10:13 - error TS2769: No overload matches this call.
  Overload 1 of 3, '(node: ReactElement<any, string | JSXElementConstructor<any>>, options?: MountRendererProps | undefined): ReactWrapper<any, Readonly<...>, Component<...>>', gave the following error.
    Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any, string | JSXElementConstructor<any>>'.
      Types of property 'type' are incompatible.
        Type 'string | ComponentType<any>' is not assignable to type 'string | JSXElementConstructor<any>'.
          Type 'ComponentClass<any, {}>' is not assignable to type 'string | JSXElementConstructor<any>'.
            Type 'ComponentClass<any, {}>' is not assignable to type 'new (props: any) => Component<any, any, any>'.
              Property 'refs' is missing in type 'Component<any, {}>' but required in type 'Component<any, any, any>'.
  Overload 2 of 3, '(node: ReactElement<any, string | JSXElementConstructor<any>>, options?: MountRendererProps | undefined): ReactWrapper<any, any, Component<...>>', gave the following error.
    Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any, string | JSXElementConstructor<any>>'.
  Overload 3 of 3, '(node: ReactElement<any, string | JSXElementConstructor<any>>, options?: MountRendererProps | undefined): ReactWrapper<any, unknown, Component<...>>', gave the following error.
    Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any, string | JSXElementConstructor<any>>'.

10             <Homepage/>
               ~~~~~~~~~~~

  node_modules/@types/react/index.d.ts:501:9
    501         refs: {
                ~~~~
    'refs' is declared here.

@types/react の最新バージョンと Enzyme の間に何らかの競合がありますか?もしそうなら、この型宣言を上書きするためのベストプラクティスはありますか?

回答 #1

このエラーの原因は、preactにおけるまだ解決されていない型定義の問題です。解決策は、node_modules/preact/src/index.d.ts に行を追加することです。componentDidCatch を検索し、その後に次の行を追加してください:

refs: { [key: string]: Component<any> | Element; };.

これにより、preact の Component インターフェースに欠けている refs メンバーが追加されます。

インストールされたノードモジュールをパッチしたくない場合は、この問題で言及されているように、tsconfig.jsonファイルにパスマッピングを追加してください。

    {
    "baseUrl": "./",
    "paths": {
      "react": ["./node_modules/preact/compat/"],
      "react-dom": ["./node_modules/preact/compat/"]
    }