typescriptbrowserifyvisual-studio-codetsify

Static property inheritance not working as expected


I have something like this;

TestBase.ts

export class TestBase {
    static myValue: boolean;
    constructor() {
        TestBase.myValue = true;
    }
}

Test

import {TestBase} from './TestBase'

export class Test extends TestBase {
    constructor() {
        super();
    }
}

SomeOtherClass.ts

import {Test} from './Test';
import {TestBase} from './TestBase';

export class SomeOtherClass {
    constructor() {
        var test = new Test();
        console.log(Test.myValue); // undefined
        Test.myValue = false;
        console.log(Test.myValue, TestBase.myValue); // false, true
    }
}

My IDE is suggesting that myValue is available on Test, but at runtime it does not reflect the value of TestBase.myValue. Is the IDE incorrectly suggesting that static property inheritance is allowed, or is browserify/tsify breaking something?


Solution

  • In Typescript, static primitives are not inherited in the way I was expecting, however static objects are. I was able to work around the issue by holding the value inside an object;

    TestBase.ts

    export class TestBase {
        static someObject = { myValue: boolean };
        constructor() {
            TestBase.someObject.myValue = true;
        }
    }
    

    Test

    import {TestBase} from './TestBase'
    
    export class Test extends TestBase {
        constructor() {
            super();
        }
    }
    

    SomeOtherClass.ts

    import {Test} from './Test';
    import {TestBase} from './TestBase';
    
    export class SomeOtherClass {
        constructor() {
            var test = new Test();
            console.log(Test.someObject.myValue); // true
            Test.myValue = false;
            console.log(Test.someObject.myValue, TestBase.someObject.myValue); // false, false
        }
    }