推断 TypeScript 泛型类类型

1 generics type-inference conditional-statements typescript

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
Run Code Online (Sandbox Code Playgroud)

Sha*_*son 5

目前,具有未在类中使用的泛型的类实际上具有与{}推断相同的“结构”。破坏功能的更改是错误修复,解决方法是在类内的某个位置使用“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.
Run Code Online (Sandbox Code Playgroud)