microsoft / microsoft/TypeScript
Variables that are used-before-assigned are typed without `undefined`
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 117
Description
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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked TypeScript Playground and reproduce the difference between let xx: number and let yy!: number. Trace how used-before-assigned analysis affects the reported type, and compare the existing typescript-eslint handling linked in the issue. Done means the first variable is exposed as number | undefined without breaking the diagnostic or the non-null-asserted case.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 30/100