iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

TS Type Assertions

A type assertion tells the compiler "trust me, this is type X". Use them when you know more than the type system can prove — but not as a shortcut to silence errors.

The two forms

TS
const input = document.querySelector('input') as HTMLInputElement;
const input2 = <HTMLInputElement>document.querySelector('input');  // disallowed in .tsx

The as form is preferred — it always works, including in JSX/TSX files.

When assertions help

  • DOM lookupsdocument.querySelector returns Element | null, you know it's an input.
  • JSON parsingJSON.parse returns any; assert it to your expected shape (with validation!).
  • Untyped libraries — when the type is too loose for your use case.

When they hurt

TS
// ✗ Lying to the compiler — runtime crash incoming
const x = 'hello' as number;     // error — incompatible

// ✗ Double assertion — escape hatch, dangerous
const y = 'hello' as unknown as number;

// ✗ "as any" silences errors but loses all safety
const z = someApi() as any;

satisfies — a safer alternative (5.0+)

satisfies checks that a value matches a type WITHOUT widening the inferred type:

TS
type Colors = Record<string, string | [number, number, number]>;

const palette = {
    red:   [255, 0, 0],
    green: '#0f0',
} satisfies Colors;

palette.red[0];      // OK — knows it's a tuple, not string
palette.green.toUpperCase();   // OK — knows it's a string

Const assertions

TS
const ROLES = ['admin', 'user', 'guest'] as const;
type Role = typeof ROLES[number];   // 'admin' | 'user' | 'guest'
Tip: Reach for satisfies before as. Reach for runtime validation (Zod, Valibot, ArkType) before either, when the data comes from JSON or an API.

Example

Example
const input = document.querySelector('input') as HTMLInputElement;
// or: const input = <HTMLInputElement>document.querySelector('input');

// const x = 'hello' as number;  // ✗ error — incompatible
const y = 'hello' as unknown as number;  // ✓ escape hatch (be careful)
Try it Yourself »

Exercise

JSX-safe type assertion keyword.

const x = value T;

Test yourself

Q1. Preferred assertion syntax is…
Q2. A safer alternative to "as" when matching a type is…
Q3. Double assertion ("as unknown as T") is…

Discussion

Loading…