【发布时间】:2021-12-06 02:19:16
【问题描述】:
我想实现这样的事情,以便可以推断出Component 的类型,从而可以自动安全地键入props。
type ComponentsType<T extends React.FC<any>> {
[key: string]: {
Component: T;
props?: React.ComponentProps<T>
};
}
const components: ComponentsType = {
RedButton: {
Component: Button,
props: { // <- this should be automatically typed to take props of Button
color: 'red'
}
},
BlueButton: {
Component: Button,
props: { // <- this should be automatically typed to take props of Button
color: 'blue'
}
},
FullWidthCard: {
Component: Card,
props: { // <- this should be automatically typed to take props of Card
variant: 'full-width'
}
},
}
但上面的输入不起作用,因为通用部分位于对象 AKA components 的根上,而不是在每个属性 AKA RedButton 或 FullWidthCard 上。
那么有没有办法让 typescript 一个一个地遍历它们并一个个地推断出组件?
谢谢
【问题讨论】:
标签: reactjs typescript type-inference