考虑以下虚拟 HOC
interface SelectOption {
value: string;
label: string;
}
interface HOCProps {
value: string | SelectOption;
}
const testHOC = <P extends HOCProps>(Component: React.ComponentType<P>): React.ComponentType<P> =>
class Wrapper extends React.Component<P> {
constructor(props: P) {
super(props);
console.log(this.props.value);
console.log(props.value);
}
render() {
return <Component {...this.props} />;
}
};
Typescript 按预期识别 props.value
:
(property) HOCProps.value: string | SelectOption
但是在 this.props.value
中我得到了不同的结果:
(property) value: P["value"]
如何修复类型注释,以便 typescript 正确推断 this.props
?
附: codesanbox link to the code in question
最佳答案
您看到 this.props
之间差异的原因和 props
在你的构造函数中,它们实际上是不同的类型。
props
键入为 P
在构造函数中,同时 this.props
在 React.Component
中定义作为props: Readonly<P> & Readonly<{ children?: ReactNode }>;
Readonly
在 typescript 库中定义为 mapped type ,因此您在悬停时会看到 P["value"]
因为这是从映射类型中提取的。
typescript 维护者已提出此问题,multiple times一直fixed .
但由于某种原因,向您显示类型的引擎可能无法解析这些映射类型。
使用 JetBrains IntelliJ,类型解析正确,而在 codesandbox 中我只看到未解析的类型 P["value"]
它指的是映射类型...
这个问题也可以在这个最小的例子中看到:
interface Base {
value: string | number;
}
const test = <T extends Base>(a: T, b: Readonly<T>) => {
console.log(a.value, b.value);
}
根据维护者的说法,这是 typescript 的一个已知设计限制:https://github.com/microsoft/TypeScript/issues/32932#issuecomment-522353713
关于reactjs - Typescript 无法正确推断 HOC 中的 this.props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57479489/