Type Assertions

Tell the compiler you know a value's type better than it does.

Syntaxconst el = value as string;

A type assertion lets you override TypeScript's inferred type using the as keyword. It says "trust me, this value is of this type".

Assertions do not convert or check anything at runtime — they only affect type checking. Use them sparingly and only when you truly know the type.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A developer asserts a DOM query result as HTMLInputElement to access the value property without a type error.
  • An API response typed as unknown is asserted to a known interface after manual validation.
  • A JSON.parse result is asserted to a specific type when the developer knows the data shape from documentation.

More examples

Assert DOM element type

Uses as to tell TypeScript that the generic HTMLElement returned by getElementById is actually an HTMLInputElement.

Example · ts
const input = document.getElementById('username') as HTMLInputElement;
console.log(input.value); // .value is available on HTMLInputElement

Assert after JSON.parse

Asserts the any-typed JSON.parse result to a known interface, giving the variable its expected type immediately.

Example · ts
interface User {
  id: number;
  name: string;
}

const raw = '{"id":1,"name":"Alice"}';
const user = JSON.parse(raw) as User;
console.log(user.name);

Double assertion via unknown

Shows the two-step assertion pattern (through unknown) needed when TypeScript rejects a direct incompatible assertion.

Example · ts
// Force a type change when TypeScript rejects a direct assertion
const value: number = 42;
const str = value as unknown as string; // unsafe but sometimes necessary

Discussion

  • Be the first to comment on this lesson.