microsoft / microsoft/TypeScript

Variables that are used-before-assigned are typed without `undefined`

Aperta
#53,306 2 commenti 2 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Awaiting More Feedback Suggestion
Lingua principale
Go
Stelle
111k
Fork
14.3k
Merge medio
1g 19h
PR unite (30g)
117

Descrizione

Bug Report

🔎 Search Terms

variable use before assign

🕗 Version & Regression Information
  • This is the behavior in every version I tried
⏯ Playground Link

Playground link with relevant code

💻 Code
let xx: number;

  xx.toFixed();
// ^?
// typeof xx === number ❌

let yy!: number;

  yy.toFixed();
// ^?
// typeof yy === number ✅
🙁 Actual behavior

TS reports the type of the used-before-assigned variable xx as number, and reports error Variable 'xx' is used before being assigned. (2454)

🙂 Expected behavior

TS reports the type of xx as number | undefined.

Additional info

This behaviour makes it difficult for us to write lint rules because when we attempt to check if the variable is undefined, the type system reports that it is not.

Examples:

  • checking for unnecessary conditions based on types
    • if (xx != null) {} The types say xx is number, so != null looks like it's unnecessary.
  • checking for unnecessary type assertions
    • xx! Again the types say xx is number, so the non-null assertion looks like it's unnecessary.

Example issue:

In the past we've manually coded up logic to do used-before-assigned checks where necessary - but it's pretty gnarly code to maintain and we have to ensure that we cover this case in our implementation.

It would be great if TS reported the "correct" type here with undefined.

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia con il TypeScript Playground collegato e riproduci la differenza tra let xx: number e let yy!: number. Traccia il modo in cui l’analisi dell’uso prima dell’assegnazione influisce sul tipo riportato e confronta la gestione esistente di typescript-eslint collegata nell’issue. Il lavoro è completato quando la prima variabile viene esposta come number | undefined senza rompere la diagnostica o il caso con asserzione non-null.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
typescript
Ambito
compilers
Tipo di issue
Bug
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
30/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.