TypeScript Tutorial · Generics and Type Manipulation · Lesson 21 of 25
TypeScript Type Assertions and satisfies
as, non-null assertions, as const and the satisfies operator.
Type assertions
value as Type tells the compiler "trust me". It performs no runtime check — if you're wrong, you get a runtime bug. Prefer narrowing; use assertions only when you know more than the compiler (e.g. DOM lookups).
const raw: unknown = JSON.parse('{"id": 1, "name": "Ada"}');
const user = raw as { id: number; name: string };
console.log(user.name);
const wrong = JSON.parse('{"id": 1}') as { id: number; name: string };
console.log(wrong.name?.toUpperCase()); // compiles, but name is really undefined
const scores = new Map([["ada", 10]]);
const adaScore = scores.get("ada")!; // we know the key exists
console.log(adaScore + 1);
Output
Ada undefined 11
The non-null assertion value! removes null/undefined from a type — the same caveat applies. See the type assertion output puzzle.
as const
as const makes literals as narrow as possible and everything readonly.
satisfies
satisfies checks that a value matches a type without widening the value's inferred type — you keep autocomplete for the exact keys:
type Route = { path: string; auth?: boolean };
const routes = {
home: { path: "/" },
dashboard: { path: "/dashboard", auth: true },
} satisfies Record<string, Route>;
console.log(routes.dashboard.path); // autocomplete knows "home" and "dashboard"
const sizes = ["S", "M", "L"] as const;
console.log(sizes.length, sizes[2]);
Output
/dashboard 3 L
Test yourself
Does value as User check the value at runtime?
YesNo — it only changes the compile-time type
Show answer
Answer: No — it only changes the compile-time type
Practice next
- Type Assertions Don't Convert · coding problem
- readonly and as const at Runtime · coding problem