TypeScript:静态属性和继承

Kor*_*sik 5 inheritance static typescript typescript1.8

我是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"
Run Code Online (Sandbox Code Playgroud)

TypeScript Playground链接

此代码运行正常,两个警报按预期显示.

但是 TypeScript编译器会抛出错误:Property "Items" does not exist on type "Function"

我理解这个警告,从TypeScript的角度来看它是完全正确的,但是如何在编译器满意的同时实现相同的结果呢? this.Items.FOO显然不起作用,我没有找到self相应或类似的东西......

我错过了什么吗?

提前致谢!

mk.*_*mk. 5

我理解这个警告,从TypeScript的角度来看,它是完全正确的

对 - 这类似于继承,但它不会也不应该通常适用于您的静态属性.要解决此问题,请使用any以下命令禁用类型检查:

alert((<any>this.constructor).Items.FOO);
Run Code Online (Sandbox Code Playgroud)

转换旧的js代码时经常会出现这种情况,但在编写新的TS代码时应该避免这种情况.如果你想正确地做到这一点,你需要(你可能知道)getItems在你的两个类中实现和覆盖一个或类似的方法来返回相应的Items,并从中调用该方法show.


Nit*_*mer 5

今天有一个类似的问题:在TypeScript的子类中引用不带名称的类以使用不同的静态方法

这里有一个讨论/建议this.constructor返回正确的类型:T.constructor应该是T类型

至于目前为您提供的解决方案:

完全没有静态:

class A {
    public show() {
        alert(this.getItems().FOO);
    }

    protected getItems() {
        return {
            FOO: 'A'
        }
    };
}

class B extends A {
    protected getItems() {
        return {
            FOO: 'B'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

操场上的代码

静态typeof

class A {
    public static Items = {
        FOO: 'A'
    };

    public show() {
        alert((<typeof A | typeof B> this.constructor).Items.FOO);
    }
}
Run Code Online (Sandbox Code Playgroud)

操场上的代码

静态与构造函数接口:

interface AConstructor {
    new (): A;
    Items: any;
}

class A {
    public static Items = {
        FOO: 'A'
    };

    public show() {
        alert((this.constructor as AConstructor).Items.FOO);
    }
}
Run Code Online (Sandbox Code Playgroud)

操场上的代码