-
Notifications
You must be signed in to change notification settings - Fork 12.8k
typeof foo === "array" causes type narrowing #13771
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
at runtime an array has typeof use |
@mhegazy I think that's the point. The check is narrowing, but it shouldn't be. I can confirm it's narrowing on all |
:D. that was dump.. you are right, since the typeof is not one we know about, we excluding the primitives, but fail to exclude "object" as well. |
From the spec, section 4.24: "A type guard of the form So |
@mhegazy had an even cleverer idea: make We previously discussed this at #9506 and decided not to do it, but I think it's worth revisiting, especially if we provide completions for binary comparisons with string literal unions. @Andy-MS points out that there is a ts-lint rule that checks this, so if we decide to take the PR, they will be able to get rid of that rule. |
TypeScript Version: 2.1.5 / nightly (2.2.0-dev.20170130)
Code
Expected behavior:
Compilation should fail with a type error, because in the final line,
ourRelationship
has typestring | Array<string>
, and arrays do not have asubstring
method.Actual behavior:
The if-throw is misinterpreted as a type narrowing from
string | Array<string>
tostring
. Compilation succeeds, and the generated javascript produces the runtime type errorourRelationship.substring is not a function
.I'm no pro at javascript, so maybe this is an allowance for some obscure browser/environment which handles
typeof
differently, but in all the environments I looked at,typeof [] === "object"
.The text was updated successfully, but these errors were encountered: