microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.7k stars 12.45k forks source link

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

Open kirkwaiblinger opened 1 week ago

kirkwaiblinger commented 1 week ago

🔎 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.

kirkwaiblinger commented 6 days ago

@RyanCavanaugh Sorry to ping, but I see the label has changed to "Awaiting More Feedback" but there's no other discussion. Is there anything you need from me or is discussion waiting on something else?

RyanCavanaugh commented 6 days ago

Neither? For feedback like this we would be wanting to hear from more than one person encountering a particular kind of situation.

kirkwaiblinger commented 6 days ago

Ah, gotcha, ok. I misunderstood what the label meant. Thanks for clarifying!