TypeScript:静态属性和继承
TypeScript: static properties and inheritance
我是 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
等价物或类似的东西...
我是不是漏掉了什么?
提前致谢!
I understand the warning and it's totally right from a TypeScript point of view
对 - 这有点像继承,但它通常不会也不应该对您的静态属性起作用。要解决此问题,请使用 any
:
禁用类型检查
alert((<any>this.constructor).Items.FOO);
这种情况在转换旧的js代码时经常出现,但在编写新的TS代码时应该避免。如果你想正确地做到这一点,你需要(你可能知道)在你的两个 类 到 return 中实现并覆盖 getItems
或类似的方法 Items
,然后从 show
.
调用该方法
今天有一个类似的问题:。
这里有 discussion/suggestion 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 AConstructor {
new (): A;
Items: any;
}
class A {
public static Items = {
FOO: 'A'
};
public show() {
alert((this.constructor as AConstructor).Items.FOO);
}
}
我是 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
等价物或类似的东西...
我是不是漏掉了什么?
提前致谢!
I understand the warning and it's totally right from a TypeScript point of view
对 - 这有点像继承,但它通常不会也不应该对您的静态属性起作用。要解决此问题,请使用 any
:
alert((<any>this.constructor).Items.FOO);
这种情况在转换旧的js代码时经常出现,但在编写新的TS代码时应该避免。如果你想正确地做到这一点,你需要(你可能知道)在你的两个 类 到 return 中实现并覆盖 getItems
或类似的方法 Items
,然后从 show
.
今天有一个类似的问题:
这里有 discussion/suggestion 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 AConstructor {
new (): A;
Items: any;
}
class A {
public static Items = {
FOO: 'A'
};
public show() {
alert((this.constructor as AConstructor).Items.FOO);
}
}