Intermediate · 6 of 16 · 12 min read
Type assertions
Overruling the compiler with as and ! — what they emit, the one rule that constrains them, and why a guard is almost always the better tool.
- Type assertions
An assertion tells the compiler to stop inferring and believe you. It is not a conversion, not a check, and not visible at runtime — which makes it the fastest way to make an error go away and the fastest way to put a crash somewhere else.
What as does
const input = document.getElementById("name") as HTMLInputElement;
console.log(input.value);
// Emitted JavaScript:
// const input = document.getElementById("name");
// console.log(input.value);
The annotation is gone and nothing was checked. The one guard rail is that the two types must overlap — you can widen or narrow, not swap:
// const bad = "hello" as number;
// Conversion of type 'string' to type 'number' may be a mistake because neither
// type sufficiently overlaps with the other.
const forced = "hello" as unknown as number; // the documented escape hatch
console.log(typeof forced); // "string" — the assertion lied
The double assertion through unknown is how you get past that rule, and the fact that it needs
two steps is the language telling you something.
There is an older angle-bracket syntax, <HTMLInputElement>el, which does the same thing and
collides with JSX — so as is what you will see.
The non-null assertion
const el = document.getElementById("app")!;
el.innerHTML = "ready";
! removes null and undefined from a type, with no check and no emit. It is reasonable where
the absence is genuinely impossible and a hidden crash everywhere else — and
Cannot set properties of null is not a message that tells you which ! was wrong.
// Handle it:
const maybe = document.getElementById("app");
if (maybe) maybe.innerHTML = "ready";
// Or fail with something readable:
function required<T>(value: T | null | undefined, what: string): T {
if (value == null) throw new Error(`${what} is missing`);
return value;
}
const el = required(document.getElementById("app"), "#app");
el.innerHTML = "ready";
The helper costs three lines once and turns every future failure into a sentence naming the thing that was absent.
as const is the opposite tool
The spellings look related and the intent is reversed:
type Method = "GET" | "POST";
const widened = { method: "GET" }; // method: string
const asserted = { method: "GET" as Method }; // override: trust me
const exact = { method: "GET" } as const; // be more precise
function send(method: Method) {}
send(asserted.method);
send(exact.method);
console.log(exact.method);
as T overrules the compiler and checks nothing. as const asks it to be more precise
than its default widening, and checks everything. One is a risk; the other is free.
as T |
as const |
satisfies T |
|
|---|---|---|---|
| Checks the value | no | n/a | yes |
| Keeps the inferred type | no — becomes T |
yes, narrowed | yes |
| Emits anything | no | no | no |
| Catches a typo | no | no | yes |
Which gives a simple rule: anywhere you were about to write as on an object literal, you
probably wanted satisfies.
type Palette = { primary: string; secondary: string };
// const bad = { primary: "#fff", secondry: "#000" } as Palette; // typo survives
// const caught = { primary: "#fff", secondry: "#000" } satisfies Palette; // reported
const good = { primary: "#fff", secondary: "#000" } satisfies Palette;
console.log(good.primary);
When an assertion is the right answer
Three cases where there is genuinely nothing better.
The DOM, where the type is wider than the truth. getElementById returns
HTMLElement | null because it cannot know what you asked for:
const input = document.querySelector("#email") as HTMLInputElement | null;
if (input) console.log(input.value);
Note the | null kept in the assertion — asserting the element type is reasonable, asserting that
it exists usually is not.
A generic the compiler cannot verify. Spreading inside a constrained generic is provably safe to a human and not to the checker:
function reset<T extends { count: number }>(item: T): T {
return { ...item, count: 0 } as T; // the spread keeps every member of T
}
console.log(reset({ count: 5, name: "Ana" }).name); // "Ana"
Immediately after a check you performed. Here the assertion only restates what the code just proved — though a predicate expresses it better.
When it is the wrong answer
interface User { id: number; name: string }
// Wrong: the annotation is a claim about data nobody inspected.
const a = JSON.parse(input) as User;
// Right: the type is the *result* of a check.
function isUser(value: unknown): value is User {
return (
typeof value === "object" && value !== null &&
typeof (value as User).id === "number" &&
typeof (value as User).name === "string"
);
}
const parsed: unknown = JSON.parse(input);
const b = isUser(parsed) ? parsed : null;
console.log(b?.name);
declare const input: string;
Both give you a User as far as the compiler is concerned. Only one of them has looked.
A rule for reviews
An assertion is a place where the type system stopped helping, so it deserves the same scrutiny as a disabled lint rule:
- Can a guard express it? Then use a guard — it checks, and it narrows the
elsetoo. - Is it
ason an object literal? Then it probably wantedsatisfies. - Is it
!on something from the DOM, storage or an API? Then it is a crash with no message. - Is it
as unknown as T? Then say in a comment why the two do not overlap.
// Worth a comment, because the next reader will ask:
// The worker protocol guarantees this shape; see protocol.md.
const message = event.data as unknown as WorkerMessage;
declare const event: { data: unknown };
interface WorkerMessage { type: string }
console.log(typeof message);
Common mistakes
Using as to silence an excess property error
Mistake. const options = { timeuot: 1 } as Options.
Why it fails. The excess property check was the one thing that would have caught the typo,
and the assertion turned it off.
What to do instead. Fix the name, or use satisfies Options.
! as punctuation
Mistake. Adding ! wherever the compiler complains about undefined.
Why it fails. Each one is an unchecked promise, and the crash it eventually causes names a
property rather than the assumption that was wrong.
What to do instead. Narrow, default with ??, or throw with a message naming what was
missing.
Asserting in a generic without saying why
Mistake. as T sprinkled through a generic helper to make it compile.
Why it fails. Some of those are genuinely safe and some are not, and nothing distinguishes
them six months later.
What to do instead. Keep them rare, and leave a one-line comment on each saying what makes it
safe.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
What does value as Target actually do?
The non-null assertion removes null and undefined from a type without checking for them.
What is the risk in this line?
const el = document.getElementById("app")!;
el.innerHTML = "ready";When is as const the right tool rather than as SomeType?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.