interface featureType<Props=any, State=any> {
initialState: State;
props: Props;
processState: (props: Props, state: State) => any;
}
const feature1Comp: featureType = {
initialState: { lastName: '' },
props: { firstName: 'eliav' },
processState: (props, state) => {
props; // type should be {firstName: string} but instead is any
},
};
为什么 props
类型没有被推断出来?我错过了什么?
quick playground here (网址已被剪切,因此请复制粘贴代码)
(我发布这个问题只是因为找到该问题的解决方案需要花费太多时间,而且这是 typescript 的常见用法)
最佳答案
- 将类型和接口(interface) (FeatureType) 大写 - 这是惯例
- 如果您使用泛型,则应将它们提供给您的类型定义:
const feature1Comp = FeatureType<{ firstName: string}, any>
将泛型视为一种“类型函数”。如果您不提供具体类型,则将使用默认值,因此 TS 假定 Props 和 State 的类型为 any。
更新:这是推理的内容
interface Component<P,S> {
initialState: S,
props: P,
processState: (props: P, state: S) => any
}
function createComponent<P, S>(arg: Component<P, S>): Component<P, S> {
return arg;
}
const x = createComponent({
initialState: 'someValue',
props: { firstName: 'Elias' },
processState: (p, s) => {
console.log(p.firstName) // Works
console.log(p.lastName) // Error
}
})
关于javascript - typescript 从其他属性的类型推断 prop 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69546606/