2
我不明白爲什麼需要打字原稿明確泛型類型定義爲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,那麼該代碼片段運行時沒有錯誤,但編譯器在每種情況下仍然會將泛型類型解析爲BaseType,而我不明白爲什麼。 –