-
Notifications
You must be signed in to change notification settings - Fork 12.8k
TypeScript doesn't respect declared function argument type definition #51487
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
Assignment narrows the variable. This is working as intended. You can use the new |
Could you give an example as to how |
Nevermind, I talked without verifying. |
Yep, that does fix it. I still find it kind of odd that assignment narrow the type of a variable whose type is explicitly declared, but oh well. I mean in C#, |
C# doesn't have union types, so the argument is moot. |
This used to not be the case, and people found that behavior very annoying and inconsistent, so we changed to this other behavior which is apparently also very annoying and inconsistent. Can't win 'em all π |
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Bug Report
π Search Terms
argument type inconsistent respect function definition
π Version & Regression Information
β― Playground Link
Playground link with relevant code
π» Code
π Actual behavior
When a variable is declared in the same block and assigned
undefined
, even when its type is explicitly declared to have| number
, its type is treated asnull | undefined
rather thannumber | null | undefined
when passed to a function. I guess TS thinks it's being helpful here, but it seems to me like annoying inconsistent behaviour that breaks my type guard function when I've explicitly told TS that the variable type should be considered| number
. Because of this behaviour, in that circumstance, myisSpecified
function no longer acts as a type guard againstnull | undefined
and I get an error from TS.π Expected behavior
TS should always respect the explicit type that the variable is declared to be whether it's a function argument or declared in the same code block as a
const
.The text was updated successfully, but these errors were encountered: