[英]How to get the generic type of class in TypeScript
我需要尝试将泛型类型传递给 TypeScript 中的类。
请参阅下面的示例,我使用'hello' | 'goodbye'
'hello' | 'goodbye'
然后,我想创建一个函数,并将该类型的参数传递给原始类。
这可能吗?
class MyTestClass<T> {
doSomething = (myType: T, count: number) => {
// ...
}
}
const myTest = new MyTestClass<'hello' | 'goodbye'>()
const myNewMethod = (subType: typeof myTest) => {
// I want subType to be 'hello' | 'goodbye'
}
您可以使用带有infer
关键字的条件类型从MyTestClass<U>
中提取U
type subType = typeof mytest extends MyTestClass<infer U> ? U : never;
在这里,如果myTest
是任何类型的MyTestClass<X>
,那么subType
将是X
,否则它将never
(这永远不会发生,因为您的myTest
明确是MyTestClass
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.