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
aschanges what the compiler believes, never what the value is.
const input = document.getElementById("new-title") as HTMLInputElement;
input.value; // fine: HTMLInputElement has a value propertyWithout 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 numberdoes not turn text into a number. - No check at runtime. The compiled JavaScript is just
document.getElementById("new-title"). Theas HTMLInputElementvanishes. 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 overlapYou 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.