【问题标题】:Typescript generic type for a React componentReact 组件的 Typescript 通用类型
【发布时间】:2022-12-11 15:42:43
【问题描述】:

我试图弄清楚如何为数据条目编写正确的类型,以便它接受任何带有道具的组件

例子:

const A = (props: { a: number }) => <>{props.a}</>
const B = (props: { b: string }) => <>{props.b}</>

type Data = {
  [id: string]: <P>(props: P) => JSX.Element | null
}

const data: Data = {
  aa: (props: Parameters<typeof A>[0]) => A(props),
  bb: (props: Parameters<typeof B>[0]) => B(props)
}

const Usage = () => (
  <>
    A: {data.aa({ a: 12 })}
    B: {data.bb({ b: 'hi' })}
  </>
)

即使我已经为每个组件指定了道具类型,我仍然会收到此错误:

TS2322: Type '(props: Parameters<typeof A>[0]) => JSX.Element' is not assignable to type '<P>(props: P) => Element | null'.
  Types of parameters 'props' and 'props' are incompatible.
    Type 'P' is not assignable to type '{ a: number; }'

我应该在 Data 类型中写什么以便它接受任何组件?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    如果您已经安装了@types/react@types/react-dom,您将已经定义了大多数反应类型。

    对于函数组件,有 FunctionComponentFC 的简称。它也是通用的,因此您可以指定道具类型。

    const A: FC<{ a: number }> = ({ a }) => <>{a}</>;
    const B: FC<{ b: number }> = ({ b }) => <>{b}</>;
    
    type Data = {
      [id: string]: FC<any>;
    };
    
    const data: Data = {
      aa: A,
      bb: B,
    };
    
    const Usage = () => (
      <>
        A: {data.aa({ a: 12 })}
        B: {data.bb({ b: 'hi' })}
      </>
    );
    

    【讨论】:

      猜你喜欢
      • 2019-11-18
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      • 2019-07-27
      相关资源
      最近更新 更多