【问题标题】:How to type an object that contains a React component as a property and also that component's props as another property?如何键入一个包含 React 组件作为属性以及该组件的道具作为另一个属性的对象?
【发布时间】:2021-07-15 02:11:03
【问题描述】:

假设我有一个结构如下的对象:

{
  Component, //<--- the component
  props, //<--- the props of the component
}

我想为这个对象创建一个泛型类型,以便它接受 component 并将该组件的 props 类型推断为 props 属性。

这是我通过引用 post 尝试创建的类型,但它并不符合我的预期。

type Object<P = {}> = {
  Component: React.ComponentType<P> | React.ElementType;
  props?: React.ComponentProps<typeof P>;
} & P;

我的实现

doSomething({
  Component: AnotherComponent,
  props: {
    ...// AnotherComponent's props
  }
})

doSomething 是一个接受object 作为参数的函数。

我对 typescript 很陌生,在 TS 文档中找不到答案。如果有人可以指导我,我将非常感激。

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    创建一个泛型接口,其中 props 是泛型参数,然后从这些 props 构造组件类型。

    interface WrapComponent<P> {
        Component: React.ComponentType<P>
        props: P
    }
    

    现在在您的函数中,只需确保将泛型参数转发到接口,以便可以推断出正确的道具类型:

    function doSomething<P>({ Component, props }: WrapComponent<P>) {
        return <Component {...props} />
    }
    
    doSomething({
        Component: ({ a }: { a: number }) => <>{a}</>,
        props: { a: 123 },
    })
    

    See typescript playground for working example

    【讨论】:

    • 太棒了!这完美地工作。这个例子帮助我更好地理解泛型类型。非常感谢!
    猜你喜欢
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    相关资源
    最近更新 更多