microsoft / microsoft/TypeScript

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

Open
#53,306 2 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
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 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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.