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)

Most upvoted comments

There literally can’t be anything I know the compiler doesn’t

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 😃

There literally can’t be anything I know the compiler doesn’t

Either you underestimate yourself or you overestimate the compiler.

Every day I find out TypeScript is the JavaScript of programming languages and JavaScript is the JavaScript of JavaScript.

I took too long writing up a response here and everyone has already said what I was going to say except:

this issue was unfortunately not filed properly; there’s a template you’re supposed to use, and you presumably chose the one about #9998 which is automatically marked as a duplicate. I would suggest you go back and file it according to the instructions, but even if you do that it will be swiftly marked as “Working as Intended” or “Not a defect” or “We Like it Like That” or something and then closed. So you might want to just close it yourself?

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.

here it does know that

At the site of the assertion, Typescript only knows that a is a string | number, so it seems reasonable that it might be just a string, 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 to f in your program, observe the arguments to all of them, and then flow that information back into the body of f.