microsoft / microsoft/TypeScript

Uninitialized local check still permits provably erroneous use-before-assign in closure

Open
#60,181 5 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

🔎 Search Terms

uninitialized, local, use before assign, control flow

🕗 Version & Regression Information
⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.7.0-dev.20240925#code/DYUwLgBAZg9jBcEDOYBOBLAdgcwNwCh8BjGTFZcAMTggF4IAKASkQDcZ0ATOgPggG98ECOiiNYMAHSgcYABYQAPBACMTAUOHQa9AOQTdBYQF98xgvhAAPAA4xUkfqaA

💻 Code
let foo: string;

const setFoo = (): void => {
  if (foo.length < 1) {
    foo = 'foo';
  }
};

export {}
🙁 Actual behavior

No TS Error

🙂 Expected behavior

Variable 'foo' is used before being assigned.(2454)

Additional information about the issue

(this error is correctly reported if we never assign at all, as below)

let foo: string;

const setFoo = (): void => {
  if (foo.length < 1) {
  }
};

export {}

Related, https://github.com/microsoft/TypeScript/issues/60064.

Otherwise this can be solved by not considering assignments which occur unconditionally after a read.

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 reproduction and compare it with the additional example that already reports diagnostic 2454. Read the control-flow change in PR 55887 and related issue 60064; done means the closure read reports use-before-assign without breaking the existing no-assignment diagnostic behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.