microsoft / microsoft/TypeScript

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

Open
#43,285 1 comment 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

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!

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked TypeScript Playground reproduction and compare the emitted JavaScript with the reported initialization order. Trace how the type checker handles static property initialization during construction, then determine whether completion should be a diagnostic, an emission change, or an explicit design decision; verify the result with a regression case.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.