TypeScript: Incorrect type assertion (?) (TS failing at a textbook example why TS exists)
function f(a: string | number) {
(a as string).toLowerCase()
}
f(1)
[ERR]: "Executed JavaScript Failed:"
[ERR]: b.toLowerCase is not a function
I tried this in the TypeScript playground.
I can’t imagine how this would be allowed. I know the “as” keyword is to tell the compiler you know something it doesn’t, but here it does know that. I literally got an error because of this, isn’t that what TypeScript is to prevent?
Edit: turns out I only understood to 99% what as does and it’s very misleading
About this issue
- Original URL
- State: closed
- Created a year ago
- Reactions: 1
- Comments: 19 (9 by maintainers)
Either you underestimate yourself or you overestimate the compiler.
You tell the compiler “trust me, this is always a string, treat it as such”. The compiler trusts you, but you lied to the compiler, it’s not always a string.
When you use a type assertion to tell TypeScript you know something it doesn’t, you also take responsibility for that something being correct 😃
Every day I find out TypeScript is the JavaScript of programming languages and JavaScript is the JavaScript of JavaScript.
Yeah I clicked on that one. It’s just an explanation on other similar issues. Other than that, it’s not empty. Go and look at the template yourself, I don’t know what I could’ve done better. And why are you suggesting I refile it if it’s just going to be closed?
If undefined is not writing a comment, then this comment is null.
At the site of the assertion, Typescript only knows that
ais astring | number, so it seems reasonable that it might be just astring, so it accepts your assertion. I think you might be expecting some flavor of whole program type inference that Typescript does not do. In particular, it will not collect up every callsite tofin your program, observe the arguments to all of them, and then flow that information back into the body off.