Lesson 13 +10 XP

Type Assertions & Const Assertions

Type Assertions & Const Assertions

Sometimes you know more about a value's type than TypeScript does. Type assertions tell the compiler to treat a value as a specific type.

Type Assertions (as)

Use the as keyword to perform a type assertion:

const element = document.getElementById("my-canvas") as HTMLCanvasElement;
// element is now treated as HTMLCanvasElement rather than HTMLElement | null

Alternative angle-bracket syntax (not recommended in JSX):

const element = <HTMLCanvasElement>document.getElementById("my-canvas");

Const Assertions (as const)

as const tells TypeScript to infer the narrowest possible literal types and mark all properties as readonly.

const config = {
  endpoint: "https://api.example.com",
  port: 8080
} as const;

// config.port = 9090; // Error: Cannot assign to 'port' because it is a read-only property.
// config.endpoint is inferred as literal "https://api.example.com" (not general string)

TL;DR

  • Type assertions (val as Type) inform the compiler about specific runtime types.
  • Type assertions do NOT perform runtime conversion or validation.
  • as const locks objects/tuples into deeply immutable read-only literal types.