Type Assertions with as
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.
The shortcut
Before writing as, ask "What would happen if I am wrong?" If the answer is "a confusing crash later", check the value instead of asserting it.
What does the compiler know?
getElementByIdreturnsHTMLElement | null. It cannot see your HTML.
Use as when you truly know better and a mistake would be caught quickly. Prefer a runtime check whenever the value comes from outside your control.
Drills
Answer fast — trust the rule.
What does const n = value as number; do at runtime?
Why does "seven" as number produce a compile error?
Which syntax cannot be used in a .tsx file?
const task = JSON.parse(text) as Task; — the text is {"name": 3}. What happens?
Remember
aschanges what the compiler believes, never what the value is.- Ask "what happens if I am wrong?" before asserting.
- Trap: asserting outside data instead of checking it hides bugs until runtime.
