Skip to the workspace
Pebellslearn by building
Assertions and Type Compatibility  ›  Lesson

Type Assertions with as

as [type] 12 minA type assertion with as tells the compiler to treat a value as a more specific type; it changes nothing at runtime and is only as safe as your claim.

typescript / Type Assertions with as

Explore each scene at your own pace.

01 · The rule

The rule

Type Assertions with as

A type assertion with as tells the compiler to treat a value as a more specific type; it changes nothing at runtime and is only as safe as your claim.

Check what an assertion changes for the compiler and what it leaves unverified at runtime.

Sometimes you know more than the compiler. document.getElementById("new-title") is typed as a general HTMLElement or null, but you wrote the HTML and you know it is an <input>. A type assertion is how you pass that knowledge on — and how you take responsibility for it.

The rule

as changes what the compiler believes, never what the value is.

const input = document.getElementById("new-title") as HTMLInputElement;
input.value;   // fine: HTMLInputElement has a value property

Without the assertion, input would be HTMLElement | null, and .value would not be allowed. With it, the compiler treats input as an HTMLInputElement from then on.

What as does not do:

  • No conversion. someString as number does not turn text into a number.
  • No check at runtime. The compiled JavaScript is just document.getElementById("new-title"). The as HTMLInputElement vanishes. If the element is really a <div>, or missing, your code breaks later.

TypeScript does refuse assertions that are clearly impossible, where neither type fits into the other:

const n = "seven" as number;  // error: string and number do not overlap

You can force it through with as unknown as number, but that is a strong sign you are fighting a real problem.

A typical use is data from outside the program:

const task = JSON.parse(saved) as Task;

JSON.parse returns any, and the assertion gives you a typed Task to work with. But nothing verified the saved text. If it holds something else, you will find out when task.title.toUpperCase() crashes.

There is an older syntax, <Task>value, which means the same as value as Task. It cannot be used in .tsx files (it clashes with JSX tags), so as is the form to learn.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.