Codington
0 of 6 problems solved0%

Type Assertions

6 exercises

Type assertions tell TypeScript how to treat a value. They do not change runtime behavior—they only affect types at compile time:

const input = document.getElementById('input') as HTMLInputElement; const data = JSON.parse(text) as User;

Important: Prefer real runtime checks first! If you can test with typeof, Array.isArray, or property checks, do that. Assertions are for when the type system can't see what you know.

Special assertion: as const

const colors = ['red', 'green', 'blue'] as const; // Type: readonly ['red', 'green', 'blue'] // Not: string[]

This freezes literal types, keeping exact strings and numbers instead of widening them to string or number. Perfect for small enums and tuples.

In this category, you'll:

  • Use value as Type when you have more information than the compiler
  • Apply as const to preserve literal types
  • Understand when assertions are safe vs. risky
  • See practical scenarios where assertions solve real problems

Use assertions sparingly and deliberately—they're an escape hatch when the type system needs your help.

CodingtonCodington

© 2025 Codington. Built with TypeScript, TanStack Start and a lot of console.log().