推断TypeScript通用类类型 [英] Infer TypeScript generic class type

查看:65
本文介绍了推断TypeScript通用类类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

B扩展了通用类A.我需要能够推断B的扩展A的通用类型.请参见下面的代码.

B extends a generic class A. I need to be able to infer the generic type of the extended A of B. See code below.

我在以前的Typescript版本中成功使用了此功能,但是对于我当前使用3.2.4(也尝试了最新的3.4.5)的项目,推断出的类型似乎导致 {} 而不是 string.

I used this in previous Typescript versions successfully but for my current project using 3.2.4 (also tried latest 3.4.5) the inferred type seems to result in {} instead of string.

知道我在做什么错吗?这不可能改变吗?

Any idea what I'm doing wrong? This can't possibly have changed?

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's"泛型,然后推理将再次起作用.

Currently a class who has a generic that isn't used in the class literally has the same "structure" as {} hence the inference. The change that was made that broke your functionality was a bug fix and the workaround is to use "A's" generic somewhere inside the class and the inference will work again.

希望这会有所帮助.

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.

这篇关于推断TypeScript通用类类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆