-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Type of variable is narrowed immediately after definition #44824
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
TypeScript narrowing it to This is working as intended. You can workaround this by using |
I'm aware of the limitations regarding functions, but the |
Honestly, I'm too lazy to look it up right now. :-D But the rationale is simple. Just take this small example:
Should this code compile? According to the type annotation it can be either And TypeScript treats variable initializations just as assignments. So it's essentially:
|
Bug Report
π Search Terms
let, control flow, null, closure, lambda, arrow function
π Version & Regression Information
β― Playground Link
Playground link with relevant code
π» Code
π Actual behavior
Right after the line
let value: string | null = null;
, TypeScript narrows the type ofvalue
tonull
.π Expected behavior
Right after the line
let value: string | null = null;
, I would have expected the type ofvalue
to bestring | null
, as declared.I understand that TypeScript performs narrowing when some operation might effectively change the type of a variable. But right after the definition of a variable, I'd like TypeScript to just trust my judgement. It's completely ignoring the type I explicitly specified, resulting in wrong typing.
The text was updated successfully, but these errors were encountered: