【问题标题】:Default generics type derivation in typescript打字稿中的默认泛型类型派生
【发布时间】:2020-01-03 20:15:39
【问题描述】:

为什么“value.type”会抛出错误“Property 'type' does not exist on type 'P'”

class A<T extends {}, P = { type: keyof T, value: T[keyof T] }> {
  constructor (value: P) {
    if (value.type) {

    }
  }
}

使用extends就可以了:

class A<T extends {}, P extends { type: keyof T, value: T[keyof T] }> {
  constructor (value: P) {
    if (value.type) {

    }
  }
}

【问题讨论】:

    标签: typescript types


    【解决方案1】:

    泛型类型参数default(情况1)与泛型constraint(情况2)不同。

    案例一:类型参数默认

    class A<P = { type: string, value: unknown }> {
      constructor(value: P) {
        if (value.type) { } // error, 'type' does not exist on type 'P' (good!)
      }
    }
    
    new A({ foo: "bar" })  // P is { foo: string; }, cannot rely on 'type' to be present.
    

    您不能依赖P 在此处拥有type 属性。仅在调用者未设置类型参数(无法推断且未手动设置)时才选择默认值。但这取决于调用方。

    案例 2:通用约束

    class AExtends<P extends { type: string, value: unknown }> {
      constructor(value: P) {
        if (value.type) { } // works
      }
    }
    
    new AExtends({ value: "bar" }) // error, 'type' is missing
    new AExtends({ type: "foo", value: "bar" }) // works
    

    编译器可以确定,value: P 总是有一个属性type。它由约束 extends { type: keyof T, value: T[keyof T] } 强制执行。

    Code sample(稍微简化您的代码;例如,不需要T

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 2020-06-29
      相关资源
      最近更新 更多