Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Static variable may be undefined when constructing an object of the same class #43285

Open
Ivan-Perez opened this issue Mar 17, 2021 · 1 comment
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript

Comments

@Ivan-Perez
Copy link

Ivan-Perez commented Mar 17, 2021

Bug Report

I'm not sure whether this may be a issue that can be fixed or just keep it as is "by design". I haven't found any other issues similar to this one here, at least with the search terms I tried (sorry if someone else already reported this 🙂).

🔎 Search Terms

static, undefined, uninitialized, constructor

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about static variables, variable order initialization, etc., but none of them seem to match this.

At the moment of writing this, TypeScript version is 4.2.3.

⏯ Playground Link

Playground Link

💻 Code

class A {
    public static readonly instance: A = new A();
    public static readonly constant: number = 1;
    
    public constructor() {
        console.log(A.constant, A.constant * 5);
        console.log(A.constant.toString());
    }
}

🙁 Actual behavior

When calling the constructor to initialize the static variable instance, A.constant is not yet initialized (it's undefined), so the constructor logs undefined, NaN.

In addition, A.constant.toString() gives a javascript execution error, which even in strict mode the compiler doesn't catch.

🙂 Expected behavior

The compiler could tell that constant has type number | undefined at that moment (manually changing the type of constantto number | undefined correctly yields a compiler error) or even rearrange the generated javascript to initialize first constant and then instance (which I think it may be more difficult in more complex scenarios).

Thank you very much!

@RyanCavanaugh RyanCavanaugh added Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript labels Mar 17, 2021
@RyanCavanaugh
Copy link
Member

This is in principle detectable with current mechanics. We don't rearrange the JS output, though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

2 participants