microsoft / microsoft/TypeScript
Static variable may be undefined when constructing an object of the same class
Nessuno ha ancora preso questa issue.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.3k
- Merge medio
- 2g 4h
- PR unite (30g)
- 132
Descrizione
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!
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia con la riproduzione collegata in TypeScript Playground e confronta il JavaScript emesso con l’ordine di inizializzazione segnalato. Traccia il modo in cui il verificatore dei tipi gestisce l’inizializzazione delle proprietà statiche durante la costruzione, quindi determina se il completamento debba essere una diagnostica, una modifica all’emissione o una decisione di progettazione esplicita; verifica il risultato con un caso di regressione.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- javascript, typescript
- Ambito
- compilers
- Tipo di issue
- Bug
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100