【发布时间】:2018-01-07 03:35:42
【问题描述】:
在这种情况下,我不明白为什么 TypeScript 需要为 Child2 和 Child3 显式定义泛型类型:
abstract class Base {
public static A: string = "Fallback_A";
public DoSmthWithClassName(): string {
return "Fallback_DoSmth";
}
constructor(...args: any[]); // overload for type consistency with children
constructor(x: string)
{ }
}
// typeof any non-abstract child of Base
type BaseType = typeof Base & (new(...args: any[]) => Base);
// decorator, modifies methods and static properties
function ClassDecorator<T extends BaseType>(valueA: string): (value: T) => T {
return (value: T) => {
value.prototype.DoSmthWithClassName = () => value.name + ".DoSmth." + value.A;
value.A = value.name + valueA;
return value;
}
}
@ClassDecorator("Foo") // OK
class Child0 extends Base {
}
@ClassDecorator("Foo") // OK
class Child1 extends Base {
constructor(x: number) {
super(x.toString());
}
}
@ClassDecorator("Foo") // Unable to resolve...
class Child2 extends Base {
static X: number = 0;
}
@ClassDecorator<typeof Child3>("Foo") // OK
class Child3 extends Base {
static X: number = 0;
}
【问题讨论】:
-
如果装饰器返回类型更改为 void,则 sn-p 运行没有错误,但编译器在每种情况下仍将泛型类型解析为 BaseType,我不明白为什么。
标签: typescript typescript-generics