TypeScript: Static Properties and Inheritance

I am new to TypeScript (1.8) and I have a little problem with inheritance and static properties.

The following is the test code that I am 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"

TypeScript Playground

This code is working fine, and both warnings are displayed as expected.

BUT the TypeScript compiler throws an error:Property "Items" does not exist on type "Function"

I understand the warning, and this is perfectly true from the point of view of TypeScript, but how can I achieve the same result while the compiler is happy? this.Items.FOOobviously does not work, and I did not find an equivalent selfor something like that ...

Did I miss something?

Thanks in advance!

+4
source share
2

: 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'
        }
    }
}

( )

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

( )

+4

, TypeScript

- - , . , any:

alert((<any>this.constructor).Items.FOO);

js-, TS. , ( ) getItems , Items, show.

+4

All Articles