Ondra Žižka Ondra Žižka - 1 month ago 8
TypeScript Question

TypeScript: Reinitializing static data in a subclass? (or other mechanism to store gobal data)

I have some static data which I want to access through some API with basic logic. (Namely, it's metadata about Java classes.)

I've put the API to few static methods of a class, and the data stub to a static field.

Then, in a subclass (which is generated), I redefine the field with some array. And I could access the same field from both parent and subclass. Not sure. I suspect this used to work but stopped working as TS 2.0 got stricter.

Anyway. I am looking for a mechanism to implement this properly. I need to access it all statically, those are data used globally. In Java, I'd probably make the parent a singleton and manipulated the static data trough there in

static {}
(however horrible that may sound).

What would be the equivalent in TypeScript?

class A {
static foo = [-1];
static getLastFoo(){ return A.foo[A.foo.length-1]; }
}

class B extends A {
static foo = [1,2,3]; // Did this work in TS 1.8?
}

B.getLastFoo(); // <--- gives 3


I assume this is somehow possible through the prototypes. Not sure if TypeScript allows that though.

Answer

Your code should not work in typescript 1.8 as well, as you're doing:

return A.foo[A.foo.length - 1];

Which should always return -1, if you want it to return 3 then it should be doing:

class A {
    static foo = [-1];
    static getLastFoo() { return this.foo[this.foo.length - 1]; }
}

this in the static context is the class and not instance, so when invoking the getLastFoo function on B it will use B.foo.


Edit

This:

class A {
    static x = 3;
    static fn() {
        console.log(this);
    }
}

Compiles into this:

var A = (function () {
    function A() {
    }
    A.fn = function () {
        console.log(this);
    };
    A.x = 3;
    return A;
}());

It's clear here that this inside A.fn is A, and that this.x is the A.x.

Comments