microsoft / microsoft/TypeScript
Static variable may be undefined when constructing an object of the same class
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.3k
- Ø Merge
- 2 T. 4 Std.
- Gemergte PRs (30 T.)
- 132
Beschreibung
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
💻 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!
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit der verlinkten TypeScript Playground-Reproduktion und vergleiche das ausgegebene JavaScript mit der gemeldeten Initialisierungsreihenfolge. Verfolge, wie der Typprüfer die Initialisierung statischer Eigenschaften während der Konstruktion behandelt, und bestimme anschließend, ob die Vervollständigung eine Diagnose, eine Änderung der Emission oder eine explizite Designentscheidung sein sollte; verifiziere das Ergebnis mit einem Regressionstest.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- javascript, typescript
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100