microsoft / microsoft/TypeScript
Variables that are used-before-assigned are typed without `undefined`
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.4k
- Ø Merge
- 1 T. 19 Std.
- Gemergte PRs (30 T.)
- 117
Beschreibung
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 sayxxisnumber, so!= nulllooks like it's unnecessary.
- checking for unnecessary type assertions
xx!Again the types sayxxisnumber, so the non-null assertion looks like it's unnecessary.
Example issue:
- https://github.com/typescript-eslint/typescript-eslint/issues/453
- https://github.com/typescript-eslint/typescript-eslint/issues/6640
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.
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 dem verknüpften TypeScript Playground und reproduziere den Unterschied zwischen let xx: number und let yy!: number. Verfolge, wie die Analyse der Verwendung vor der Zuweisung den gemeldeten Typ beeinflusst, und vergleiche die im Issue verlinkte bestehende Behandlung in typescript-eslint. Erledigt bedeutet, dass die erste Variable als number | undefined ausgewiesen wird, ohne die Diagnose oder den Fall mit Non-Null-Assertion zu beeinträchtigen.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- typescript
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Klar beschrieben
- Anfängerfreundlichkeit
- 30/100