推断TypeScript通用类类型

法比奥·斯卡拉(Fabio Scala)

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
香农杰克逊

当前,具有未在类中实际使用的泛型的类具有与{}推断相同的“结构” 所做的更改破坏了您的功能,是一个错误修复,解决方法是在类内部的某个地方使用“ 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.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章