Annotations and Assertions 12 exercises
explainer

The Limits of as in TypeScript

Let's revisit the as keyword with a focus on its limitations and how to navigate around them.

Here we have a num1 constant that is being inferred as a number:

const num1 = "hello" as number; // red squiggly line under "hello" as number

This results in a TypeScript error mess

Loading explainer

Transcript

00:00 Let's go back to talking about as for a second. Here we have a number, which is const num1 equals or is being inferred as a number. And what we're saying here is we're assigning hello to it. But we can see that hello as number is actually throwing up an error. Conversion of type string to type number may be a mistake

00:18 because neither type sufficiently overlaps with the other. TypeScript is actually throwing a little bit of a wobbly here saying, you're trying to convert a string to a number, are you mad? That doesn't seem right. And you notice that there are some limits to the way that TypeScript wants to use as.

00:36 Now these limits are very, very easy to overrule. It actually gives you a hint here. If this was intentional, convert the expression to unknown first. So we can actually say hello as unknown as number perfectly easily. We can also do hello as any as number

00:53 and hello as never as number too. Just because of the way that TypeScript works because unknown is like the top type, so it's sort of related to everything. Hello is, oh sorry, never is the bottom type, so it's also related to everything. And any is kind of like a mega type, so it's sort of related to everything too.

01:10 So you can convert to any and then convert to number. You can also, if you want to, just say as number, as number, as number, as number, if you're feeling particularly cruel here. So let's see. Oh yeah, that doesn't prettify well at all. So as it does have some limits, but you can do this kind of double as.

01:30 And if you see this out in the wild, this is essentially as unsafe as just doing as any. So a dangerous, dangerous tool in the wrong hands, but as does have some little limits some places.