打字稿:通用 class 类型推断

Typescript: Generic class type inference

以下内容看起来很简单,但我不确定是什么导致了错误。我已经四处寻找了一段时间,但似乎找不到答案。

class MyClass<T > {
  property: T = 5 // Error Here: Type '5' is not assignable to type T
}

const tester = new MyClass<number>() // OK

const numberValue: number = tester.property // OK
const stringValue: string = tester.property // Error as expected

我认为 T 会被推断为 'property' 中的数字。我觉得以前工作过,但我不确定。

Typescript playground with examples


更新

这些定义也有同样的错误。

class MyClass<T extends number> {
  property: T = 5 // Error Here: Type '5' is not assignable to type T
}

class MyClass<T extends object> {
  property: T = {} // Error Here: Type '{}' is not assignable to type T
}

这应该永远不会奏效。无论您在泛型 class 或方法的定义中编写什么,都必须对 所有 可能的 T 值有效,而 class 或方法可能会被使用。如果有人做了 new MyClass<string>(),则赋值 property: T = 5 无效,因此 Tstring。仅当您 使用 通用 class 或方法时才会发生推理。