TypeScript:静态属性和继承 [英] TypeScript: static properties and inheritance
问题描述
我是TypeScript(1.8)的新手,继承和静态属性有一个小问题.
I'm quite new to TypeScript (1.8) and I have a small issue with inheritance and static properties.
请在下面找到我当前正在运行的测试代码:
Please find below the test code I'm currently running:
class A {
public static Items = {
FOO: 'A'
};
public show() {
alert(this.constructor.Items.FOO);
}
}
class B extends A {
public static Items = {
FOO: 'B'
};
}
var a = new A();
var b = new B();
a.show(); // alert "A"
b.show(); // alert "B"
This code runs fine and the two alerts are shown as expected.
但是 TypeScript编译器抛出错误:Property "Items" does not exist on type "Function"
BUT the TypeScript compiler throws an error : Property "Items" does not exist on type "Function"
我理解了警告,并且从TypeScript的角度来看这是完全正确的,但是如何在使编译器满意的同时实现相同的结果呢? this.Items.FOO
显然不起作用,我没有找到等效的self
或类似的东西...
I understand the warning and it's totally right from a TypeScript point of view, but how can I achieve the same result while making the compiler happy? this.Items.FOO
obviously does not work and I didn't find a self
equivalent or something like that...
我想念什么吗?
提前谢谢!
推荐答案
There was a similar question today: Referencing class without name to use different static method in subclasses in TypeScript.
这里有讨论/建议让this.constructor
返回正确的类型: T.constructor应该是T 类型.
There's a discussion/suggestion of having this.constructor
returning the right type here: T.constructor should be of type T.
至于目前为您提供的解决方案:
As for possible solutions for you for now:
完全没有静态:
class A {
public show() {
alert(this.getItems().FOO);
}
protected getItems() {
return {
FOO: 'A'
}
};
}
class B extends A {
protected getItems() {
return {
FOO: 'B'
}
}
}
class A {
public static Items = {
FOO: 'A'
};
public show() {
alert((<typeof A | typeof B> this.constructor).Items.FOO);
}
}
Static with constructor interface:
interface AConstructor {
new (): A;
Items: any;
}
class A {
public static Items = {
FOO: 'A'
};
public show() {
alert((this.constructor as AConstructor).Items.FOO);
}
}
( 查看全文