You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Expected behavior:
I would expect the compiler to treat the if statement as a type guard and recognise that value is a string afterwards. Actual behavior:
I get the build error "Property 'length' does not exist on type 'string | number'". If I remove the brackets around value after the typeof, i.e.
Then it compiles fine. I can therefore workaround this but it would be nice to not have to; I mainly write C# and as a result I automatically type brackets after typeof. :)
The text was updated successfully, but these errors were encountered:
The compiler honors a certain forms of type guard expressions. there are other forms that are functionally equivalent, but are not supported, such as the one referenced in the OP. The recommendation would be to use the standard form instead.
mhegazy
added
Bug
A bug in TypeScript
Won't Fix
The severity and priority of this issue do not warrant the time or complexity needed to fix it
labels
May 12, 2016
Any chance you could reconsider please? It seems inconsistent with the rest of the language, plus it's quite difficult to work out what is happening because, as you say the forms are functionally equivalent. And I naturally use brackets after typeof due to many years of C#... Took me ages to figure out what was going on!
If you can't fix it could you maybe make it an error/warning to use brackets after typeof? Or at the very least put a big note in the handbook documentation telling people to use the standard form if they want type guards to work?
it is not about this pattern, there are other ones: typeof (v) === "string" typeof v === ("string") (typeof v) === "string" typeof v === (foo(), "string")
If you can't fix it could you maybe make it an error/warning to use brackets after typeof?
it is valid JS/TS code. it just does not narrow the type. a tslint rule would be a simple addition that can catch these.
No, fair enough, I can see how it would be complex to fix! If you could add a note to the handbook stating that type guards only work with the standard form that would be good though, might save others a bit of time working out what is going wrong.
TypeScript Version:
1.8.9, used via the Visual Studio extension 1.8.31.0
Code
Expected behavior:
I would expect the compiler to treat the if statement as a type guard and recognise that value is a string afterwards.
Actual behavior:
I get the build error "Property 'length' does not exist on type 'string | number'". If I remove the brackets around value after the typeof, i.e.
Then it compiles fine. I can therefore workaround this but it would be nice to not have to; I mainly write C# and as a result I automatically type brackets after typeof. :)
The text was updated successfully, but these errors were encountered: