Well, I have a confession — I used to hate Docker. But that was three years ago. These days, I see the same pattern in pull requests every week. Developers treat TypeScript type assertions like they’re actual runtime casts. Narrator voice: they aren’t.
And sometimes you do know better than the compiler. But often, you’re just turning off the smoke alarm because the cooking is getting noisy. The one place where I almost always give type assertions a pass is DOM manipulation. TypeScript has no way of knowing what your HTML looks like at runtime.
This is where things get dangerous, though. I see this pattern constantly in React apps fetching data from a backend. The assertion as UserProfile erased the safety net. TypeScript was happy, but the browser was not.
When I see as unknown as in a code review, I stop reading. It’s a massive red flag. But not all assertions are bad. As const is arguably my favorite TypeScript feature. It locks down a literal value, making it read-only and narrowing the type from a generic primitive (like string) to the specific literal value.
After years of wrestling with this, here is my personal policy: DOM Elements — go ahead, use as HTMLInputElement. Literals — use as const everywhere. API Data — never use assertions if you can help it. If you can’t use a schema library like Zod or Valibot, write a custom Type Guard function that returns arg is MyType.
Assertions are a tool for when you know something the compiler doesn’t. Just make sure you actually know it, and you aren’t just hoping for the best. The official TypeScript documentation states that type assertions “tell the compiler ‘I know more about this type than you,’ so you can override the compiler’s type inference.”
Additionally, the TypeScript Wiki provides guidance on when to use type assertions, noting that they should be used “when you know more about the type of a variable than the compiler does.”
Finally, the TypeScript documentation on Narrowing explains that the “as” operator is used to “tell the compiler that you know more about the type of a variable than it does.”
