TypeScript theorytheory 0/50 · 0%
Types · easy

18. Type assertions and casting

Telling the compiler you know more than it does.

A type assertion (`as T`) overrides TypeScript's inferred type without changing runtime behaviour. It's a compile-time-only tool, unlike a runtime type conversion.

ts
const input = document_result as unknown; // stand-in for any external value
const amount = input as number;

const el = fetchSomething() as { value: number };

Assertions are only allowed between compatible types (you can't assert `string` to `number` directly; you'd go through `unknown` first). They should be used sparingly — prefer narrowing with `if` checks or validating input at runtime, since `as` provides no actual safety, only a compiler-level promise.

Check your understanding

  1. 1. Does `value as SomeType` change the value at runtime?

  2. 2. How do you assert between two unrelated types like `string` and `number`?

  3. 3. Why should assertions be used sparingly?