reactjs - Typescript 类型检查的通用 Props
我想编写一个组件,该组件将接收其他组件和属性,并在渲染时注入自定义属性
type InjectProps<P> = {
custom: string
} & P
interface Props<P> {
component: React.ComponentType<InjectProps<P>>
componentProps: P
}
class PropInjector<T> extends Component<Props<T>> {
...
render() {
const GivenComponent = this.props.component
return (
// in my case, Wrapper is needed for some reason.
<Wrapper>
<GivenComponent {...this.props.componentProps} custom="props" />
<Wrapper />
)
}
}
当我使用像这样定义了 props 的 Input 进行测试时,
interface InputProps {
custom: string
value: string
onChange(value: string): void
}
class Input extends Component<InputProps> { ... }
我以为 TypeScript 可以在下面的代码中推断类型并进行类型检查,但它没有报任何错误。
render() {
return (
// should throw error about not existing Input's required props like value, onChange ....
// But no error
<PropInjector component={Input} componentProps={{}} />
)
}
我如何让 Typescript 推断 P,并在使用 PropInjector 时对 componentProps 与 P 做一些类型检查?
答案#1
据我所知,目前使用 TypeScript 这是不可能的。在你的最终 render() 方法中,你没有向 PropInjector 提供泛型值。因此 TypeScript 无法知道 PropInjector 内的 T 应该是什么。
一种变通方法是像这样定义一个中间组件:
class InputPropInjector extends PropInjector<InputProps> { }
class Input extends Component<InputProps> {
render(): JSX.Element {
return (
<InputPropInjector component={Input} componentProps={{}} />
);
}
}
关于这个已经有很多讨论,希望将来能有更好的解决方案。
