我是 TypeScript (1.8) 的新手,我有一个关于继承和静态属性的小问题。
请在下面找到我当前正在运行的测试代码:
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"
此代码运行良好,两个警报按预期显示。
但是 TypeScript 编译器抛出一个错误:Property "Items"does not exist on type "Function"
我理解这个警告,从 TypeScript 的角度来看它是完全正确的,但是我怎样才能在让编译器满意的同时获得相同的结果呢? this.Items.FOO
显然不起作用,我没有找到 self
等价物或类似的东西......
我错过了什么吗?
提前致谢!
最佳答案
今天有一个类似的问题:Referencing class without name to use different static method in subclasses in TypeScript .
这里有关于让 this.constructor
返回正确类型的讨论/建议:T.constructor should be of type T .
至于目前可能的解决方案:
完全没有静态:
class A {
public show() {
alert(this.getItems().FOO);
}
protected getItems() {
return {
FOO: 'A'
}
};
}
class B extends A {
protected getItems() {
return {
FOO: 'B'
}
}
}
使用 typeof
的静态:
class A {
public static Items = {
FOO: 'A'
};
public show() {
alert((<typeof A | typeof B> this.constructor).Items.FOO);
}
}
带有构造函数接口(interface)的静态:
interface AConstructor {
new (): A;
Items: any;
}
class A {
public static Items = {
FOO: 'A'
};
public show() {
alert((this.constructor as AConstructor).Items.FOO);
}
}
关于inheritance - TypeScript:静态属性和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37732427/