简体   繁体   English

打字稿中的默认泛型类型派生

[英]Default generics type derivation in typescript

Why does "value.type" throw an error "Property 'type' does not exist on type 'P'"为什么“value.type”会抛出错误“类型 'P' 上不存在属性 'type'”

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

    }
  }
}

Using extends is OK:使用 extends 就可以了:

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

    }
  }
}

A generic type parameter default (case 1) is different from a generic constraint (case 2).泛型类型参数默认值(情况 1)与泛型约束(情况 2)不同。

Case 1: type parameter default情况一:类型参数默认

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.

You cannot rely on P to have a type property here.您不能依赖P在这里拥有type属性。 A default is only chosen, if the type parameter is not set by the caller (cannot be inferred and is not set manually).如果调用者未设置类型参数(无法推断且未手动设置),则仅选择默认值。 But that depends on the caller side.但这取决于调用方。

Case 2: generic constraint案例 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

The compiler can be sure, that value: P always has a property type .编译器可以肯定,那个value: P总是有一个属性type It is enforced by the constraint extends { type: keyof T, value: T[keyof T] } .它由约束extends { type: keyof T, value: T[keyof T] }强制执行。

Code sample (simplified your code a bit; eg T is not needed) 代码示例(稍微简化了您的代码;例如不需要T

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

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