Sub topic 20
Type assertions and comparability
This chapter assumes you know the assignability rules from the earlier chapters: structural checks, unions, literal types, and the top and bottom types. It explains the rule behind expr as T, which is looser than assignability but not unlimited.
What an assertion does
A type assertion tells the compiler to treat an expression as a different type. It changes only what the checker believes. It emits no runtime code, performs no conversion, and checks nothing when the program runs.
const value = "42" as unknown as number;
console.log(value.toFixed(2)); // compiles, throws TypeError at runtimeThe string stays a string. The assertion only silenced the compiler.
The rule: comparability in either direction
An assertion from source type S to target type T is allowed when T is comparable to S, or S is comparable to T. Otherwise the compiler reports an error.
Comparability is a relation like assignability, but more permissive in a few places. Because the check runs in both directions, you can assert in two ways:
- Upcast:
Sis assignable toT, so you move to a wider type. - Downcast:
Tis assignable toS, so you move to a narrower type.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
declare const animal: Animal;
declare const dog: Dog;
const asDog = animal as Dog; // OK: Dog is assignable to Animal (downcast)
const asAnimal = dog as Animal; // OK: Dog is assignable to Animal (upcast)
const asNumber = animal as number; // Error: neither type sufficiently overlapsThe error says the conversion "may be a mistake because neither type sufficiently overlaps with the other". The compiler is rejecting two unrelated types, not the idea of an assertion.
How comparability differs from assignability
Comparability is weaker than assignability in a few specific ways. These are the ones you meet most often.
| Situation | Assignability | Comparability |
|---|---|---|
| Union source | Every member must be assignable to the target | One member being related to the target is enough |
| `string` and a literal such as `"a"` | `"a"` to `string` only | Works both ways, so `string` can be asserted to `"a"` |
| Unrelated object shapes | Not assignable | Not comparable either, unless one is assignable to the other |
The union rule is why this compiles:
declare const input: string | number;
const asString = input as string; // OK: narrowing a union
const asStringOrBool = input as string | boolean; // OK: string overlaps
const asBoolean = input as boolean; // Error: no overlapThe literal rule is why you can assert from a widened type back to a union of literals:
type Mode = "fast" | "slow";
declare const raw: string;
const mode = raw as Mode; // OK: Mode is assignable to stringThe compiler only confirms that Mode is a possible refinement of string. It does not check that raw actually holds "fast" or "slow".
What assertions skip
An assertion is not an annotation. Compare these two lines:
interface Point {
x: number;
y: number;
}
const a: Point = { x: 1 }; // Error: property 'y' is missing
const b = { x: 1 } as Point; // OK: Point is assignable to { x: number }
const c = { x: 1, y: 2, z: 3 } as Point; // OK: no excess property checkBoth b and c compile. In b, the literal's type { x: number } is a supertype of Point, so the downcast direction succeeds, and the missing y goes unnoticed. In c, the object literal is not checked as a fresh literal, so the excess property check from the earlier chapter does not run.
If you want a check without changing the type, use satisfies (TypeScript 4.9 and later):
interface Point {
x: number;
y: number;
}
const p = { x: 1, y: 2 } satisfies Point; // OK, p keeps its precise type
const q = { x: 1 } satisfies Point; // Error: property 'y' is missingsatisfies runs the full assignability check, including excess properties, and does not override the inferred type. as does neither.
The escape hatch: assert through unknown
When the compiler rejects an assertion, you can go through a top type. Every type is assignable to unknown, and unknown is comparable to every type, so each step passes.
interface Animal {
name: string;
}
declare const animal: Animal;
const forced = animal as unknown as number; // compiles; the number is a lieRelated assertion forms
as constis a special assertion. It requests the narrowest literal types andreadonlymodifiers, and it never fails comparability. It is the fix for the widening problem shown in the literal types chapter.- Non-null assertion
x!removesnullandundefinedfrom the type ofx. It is the same trust-me contract: nothing runs at runtime, so a null value still crashes later. - Angle-bracket syntax
<T>exprfollows the same rules asas, but it is not allowed in.tsxfiles because it conflicts with JSX.
Common mistakes
- Using
asto build objects. Writing{} as Usermakes an empty object look complete. Later code then reads properties that do not exist. - Asserting parsed data.
JSON.parse(text) as Configreturnsany, andanyis comparable to everything. The compiler accepts any claim, so a bad payload fails far from the cause. - Assuming an error means the types are incompatible at runtime. Comparability is a compile-time relation about declared types. A rejected assertion tells you the declarations do not overlap, not what the value contains.
- Asserting to silence an error you do not understand. The error usually points at a real mismatch. Read the assignability failure first.
Exercise
For each line, say whether it compiles, and name the rule that decides it. declare const id: string | number; interface Shape { kind: string } interface Circle extends Shape { radius: number } declare const shape: Shape; const l1 = id as number; const l2 = shape as Circle; const l3 = shape as string; const l4 = { kind: "sq" } as Circle; const l5 = { kind: "sq" } satisfies Circle;
Show answer
l1 compiles, because for a union source one member (number) being comparable is enough. l2 compiles, because Circle is assignable to Shape, so this is a downcast. l3 fails, because Shape and string do not overlap in either direction. l4 compiles, because Circle is assignable to the literal's type { kind: string }, and assertions do not report the missing radius property. l5 fails, because satisfies runs the full assignability check and radius is missing.