【问题标题】:Infer TypeScript generic class type推断 TypeScript 泛型类类型
【发布时间】:2019-09-17 02:24:07
【问题描述】:
B 扩展了一个泛型类 A。我需要能够推断 B 的扩展 A 的泛型类型。请参见下面的代码。
我在以前的 Typescript 版本中成功使用了它,但是对于我当前使用 3.2.4 的项目(也尝试了最新的 3.4.5),推断的类型似乎导致 {} 而不是 string。
知道我做错了什么吗?这不可能改变?
class A<T> {
}
class B extends A<string> {
}
type GenericOf<T> = T extends A<infer X> ? X : never;
type t = GenericOf<B>; // results in {}, expected string
【问题讨论】:
标签:
typescript
generics
conditional
type-inference
【解决方案1】:
目前,具有类中未使用的泛型的类实际上具有与 {} 相同的“结构”,因此推断。破坏您的功能的更改是一个错误修复,解决方法是在类中的某处使用“A”泛型,推理将再次起作用。
希望这会有所帮助。
class A<T> {
hello: T = "" as any; // note that i have used the generic somewhere in the class body.
}
class B extends A<string> {}
type GenericOf<T> = T extends A<infer X> ? X : never;
type t = GenericOf<B>; // string.
【解决方案2】:
好吧,nvm 经过大量研究后自己想通了。似乎 TypeScript 在这种简单的情况下无法区分,因为这些类都是空的,相当于{}。添加属性实际上是不够的,它需要是实际引用泛型 T 的属性,以便 TypeScript 稍后正确推断泛型类型:
class A<T> {
constructor(public a: T) {}
}
class B extends A<C> {
constructor(public b: C) {
super(b);
}
}
class C {
constructor(public c: string) {
}
}
type GenericOf<T> = T extends A<infer X> ? X : never;
type t = GenericOf<B>;