kimy82
kimy82

Reputation: 4495

Typescript Static Class

I do have a static class in typescript that has an async build method like the following:

export default class DbServiceInit {
    public static myProperty: string;

    public static build = async(): Promise<void> => {
            try {
                DbServiceInit.myProperty = "ssss";
                console.log('My Static Class', DbServiceInit)
            } catch (error) { console.error(error); }
    }
}

When I am calling it like this:

await DbServiceInit.build();

It logs an empty class:

My Static Class class DbServiceInit {
}

Any help will be appreciated as I can't figure out why is this happening as I would expect the following:

My Static Class class DbServiceInit {
       myProperty: 'ssss'
    }

Playground link

Upvotes: 1

Views: 866

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075527

Remember that at runtime, you're dealing with JavaScript, not TypeScript. The runtime behavior will vary by JavaScript engine, and on what your compilation target is for TypeScript, e.g. ~ES5 or ~ES2015, but you're apparently targeting ES2015+), and on the implementation of the console being used, but at present there is no standard way to show a static property within class syntax (one is coming, but isn't here yet), so you only see what can be validly represented by the JavaScript engine.

Separately, you're not declaring a static property. You're adding one at runtime. I'd have to check the proposed spec text to be sure, but it wouldn't surprise me if the rendition of the class only included declared static properties, not ones added at runtime.

The property is there, it's just not shown in that serialization.

Upvotes: 1

Related Questions