简体   繁体   English

打字稿从其他属性的类型推断道具类型

[英]typescript infer prop type from type of other property

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
  },
};

why props type is not being inferred?为什么没有推断props类型? what am I missing?我错过了什么?

quick playground here (the URL is being cut so copy-paste the code) 在这里快速游乐场(URL 正在被剪切,因此复制粘贴代码)

(I post this question only because it takes too much time to find a solution for that issue and this is quite a common usage for typescript) (我发布这个问题只是因为找到该问题的解决方案需要太多时间,这是打字稿的常见用法)

  1. Capitalize your types and interfaces (FeatureType) - that's a convention大写您的类型和接口(FeatureType) - 这是一个约定
  2. If you use generics, you should provide them to your type definiton:如果您使用泛型,您应该将它们提供给您的类型定义:

const feature1Comp = FeatureType<{ firstName: string}, any>

Treat generics as a kind of 'type functions'.将泛型视为一种“类型函数”。 If you don't provide the concrete types, defaults will be used, so TS assumes Props and State are typed as any.如果您不提供具体类型,则将使用默认值,因此 TS 假定 Props 和 State 类型为 any。

Update: here is what will work with infering更新:这是推断的工作

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
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM