推断TypeScript通用类类型

时间:2019-04-28 03:34:26

标签: typescript generics conditional type-inference

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

2 个答案:

答案 0 :(得分:0)

好吧,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>;

答案 1 :(得分:0)

当前,具有未在类中实际使用的泛型的类具有与{}相同的“结构”,因此可以进行推断。进行的破坏您功能的更改是一个错误修复,解决方法是在类内部的某个地方使用“ A's”泛型,然后推理将再次起作用。

希望这会有所帮助。

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.
相关问题