TypeScript:静态属性和继承 [英] TypeScript: static properties and inheritance

查看:297
本文介绍了TypeScript:静态属性和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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'
        }
    }
}

(具有typeof的静态:

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);
    }
}

( 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆