【发布时间】:2020-03-15 03:02:39
【问题描述】:
我想从传递给函数的this 关键字推断当前类的类型。出于某种原因,当我将 this 作为参数传递给函数时,TypeScript 推断类型参数 T 是 this 而不是当前类类型。
下面是我正在尝试做的一个例子。我希望B 和C 类都有一个field 类型为number,但是当将this 作为参数传递时,C 类中的field 是GenericArguments<this>。当手动指定类型时,一切正常(B 类示例),但从 this 推断类型并没有给出我想要的结果。
type GenericArgument<T> = T extends A<infer R> ? R : never;
function test<T>(obj: T): GenericArgument<T> {
// do operations
// return ...;
}
class A<T> {
something: T;
}
class B extends A<number> {
field = test<B>(this); // <-- field has a type: number
}
class C extends A<number> {
field = test(this); // <-- field has a type: GenericArgument<this>
}
我是否需要一些额外的关键字来强制 TypeScript 使用当前类类型而不是多形 this?还是有其他方法可以实现这一点?
【问题讨论】:
标签: typescript function generics this type-inference