【发布时间】:2018-08-08 20:58:51
【问题描述】:
我有一个接受泛型类型参数TChildProps的组件:
type GenericFieldHTMLAttributes =
| InputHTMLAttributes<HTMLInputElement>
| SelectHTMLAttributes<HTMLSelectElement>
| TextareaHTMLAttributes<HTMLTextAreaElement>
interface FieldProps {
name: string
label?: string | React.ReactNode
component?: string | React.ComponentType
initialValue?: any
children?: React.ReactNode | FieldRenderFunction
}
class Field<TChildProps = GenericFieldHTMLAttributes> extends React.PureComponent<FieldProps & TChildProps> {
...
}
当我使用这个组件时,我希望它能够阻止我传入无法识别的道具,例如:
render() {
return (
<Form onSubmit={this.save}>
<Field foo="test" label="email" name="email" type="email" component={TextField} />
</Form>
)
}
令人惊讶的是,上面的代码编译时甚至没有任何警告,尽管foo 属性没有在任何地方定义。我尝试简化示例并得到相同的结果:
class Field<TChildProps = {}> extends React.PureComponent<FieldProps & TChildProps> {
...
}
// this still compiles without errors
<Field foo="test" label="email" name="email" type="email" component={TextField} />
TypeScript 是否按照 React.PureComponent 的类型定义在此处正常运行(顺便说一下,我在 React.Component 上对其进行了测试并得到了相同的结果),还是这是一个错误?
【问题讨论】:
标签: reactjs typescript