Sub topic 14
Type assertions and their risks
This chapter assumes you know how to annotate variables, how unions and narrowing work, and the difference between any and unknown. It covers type assertions: what they do, when they are justified, and how they cause bugs.
What an assertion does
A type assertion tells the compiler to treat a value as a type you name. It uses the as keyword.
const raw: unknown = "hello";
const text = raw as string;
console.log(text.toUpperCase()); // HELLOAn assertion exists only at compile time. It emits no JavaScript and performs no check. The compiler stops verifying the value and trusts you. If you are wrong, the error shows up later at runtime, far from the assertion.
const raw: unknown = 42;
const text = raw as string;
console.log(text.toUpperCase()); // TypeError at runtime: text.toUpperCase is not a functionCompare this with narrowing. typeof raw === "string" is a real runtime check, and the compiler learns the type from it. An assertion supplies the type with no check behind it.
The angle-bracket form
An older syntax writes the type in angle brackets before the value.
const raw: unknown = "hello";
const text = <string>raw;It behaves the same as as. It is not allowed in .tsx files, because it conflicts with JSX syntax. Most style guides prefer as, so use as throughout.
What the compiler allows
Assertions are not unlimited. TypeScript allows an assertion only when one type is assignable to the other, meaning the types sufficiently overlap. Assertions can go from a wide type to a narrower one, or the reverse.
function pick(value: string | number) {
const asString = value as string; // ok: string is part of the union
return asString;
}
const n = 5;
// const s = n as string;
// Error: Conversion of type 'number' to type 'string' may be a mistakeThe error message exists to catch likely mistakes. It does not make assertions safe, because you can still be wrong inside the allowed range.
Two types are always allowed as sources: any and unknown. Asserting from either one to any type compiles, which is why these are the most common sources of unsafe assertions.
Common legitimate uses
Assertions are justified when you know something the compiler cannot see. Typical cases follow.
DOM elements
document.querySelector returns Element | null. If you know the element is an input, you can say so.
const input = document.querySelector("#email") as HTMLInputElement;
input.value = "[email protected]";This is still a claim. If no element has that id, input is null at runtime and the assignment throws. A safer version checks:
const found = document.querySelector("#email");
if (found instanceof HTMLInputElement) {
found.value = "[email protected]";
}Values from outside the type system
JSON.parse returns any, and fetch(...).then(r => r.json()) gives any as well. Developers often assert a result type onto them.
interface User {
name: string;
age: number;
}
const user = JSON.parse('{"name":"Ada"}') as User;
console.log(user.age.toFixed(0)); // TypeError: Cannot read properties of undefinedThe data is missing age, and the compiler never noticed. An assertion on external data is a promise that nothing verifies. If the data comes from a network, a file, or a user, validate it first.
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
typeof (value as { name?: unknown }).name === "string" &&
typeof (value as { age?: unknown }).age === "number"
);
}
const parsed: unknown = JSON.parse('{"name":"Ada","age":36}');
if (isUser(parsed)) {
console.log(parsed.age.toFixed(0)); // 36
}The isUser function is a type guard. Its return type value is User tells the compiler that a true result narrows the argument. Note that the guard itself uses small assertions. They are acceptable here because each one is followed by a runtime typeof check on the property.
Narrowing the compiler cannot follow
Sometimes your logic guarantees a type but the control flow is too complex for the compiler to track.
const cache = new Map<string, number>();
cache.set("a", 1);
if (cache.has("a")) {
const value = cache.get("a") as number; // get() returns number | undefined
console.log(value + 1);
}Here the assertion is reasonable, because has was just checked. Even so, the code stays correct only as long as nobody changes the lines above it.
The non-null assertion
A postfix ! removes null and undefined from a type. It is a narrow assertion.
const map = new Map<string, number>([["a", 1]]);
const value = map.get("a")!; // type is number
console.log(value + 1);It carries the same risk as as. If the value is actually undefined, you get a runtime error with no warning. Many teams enable a lint rule against ! and handle the missing case explicitly.
const value = map.get("a");
if (value === undefined) {
throw new Error("Missing key: a");
}
console.log(value + 1);Double assertions
When two types do not overlap, a direct assertion fails. Routing through unknown forces it through.
const n = 5;
const s = n as unknown as string; // compiles
console.log(s.toUpperCase()); // TypeError at runtimeThis silences the compiler completely. Treat as unknown as T as a warning sign in review. It is almost always a mistake or a gap in the types that should be fixed at the source.
Assertions are not conversions
A common misunderstanding is that as number turns a string into a number. It does not change the value.
const input: unknown = "42";
const n = input as number;
console.log(typeof n); // "string"
console.log(n + 1); // "421"To convert, use a runtime operation such as Number(input), then check the result with Number.isNaN.
Assertions can hide missing properties
Annotating a variable and asserting an object literal behave differently.
interface Config {
host: string;
port: number;
}
const a: Config = { host: "localhost" };
// Error: Property 'port' is missing
const b = { host: "localhost" } as Config; // no error
console.log(b.port); // undefinedThe annotation checks the object and reports the missing property. The assertion accepts it, because the literal's type is a supertype of Config and so the types overlap. If you only want to check an object against a type, use an annotation or satisfies, not as.
Choosing the right tool
| Situation | Prefer | Reason |
|---|---|---|
| Data of unknown shape | `unknown` plus a type guard | Checks at runtime |
| Value that may be `null` | An explicit `if` check | Handles the failure case |
| Checking an object against a type | Annotation or `satisfies` | Reports missing properties |
| Compiler cannot follow valid logic | `as` with a comment | Documents your claim |
| Types do not overlap | Fix the types | `as unknown as T` hides the error |
Practical guidelines
- Prefer narrowing over assertions whenever a runtime check is possible.
- Validate data from outside your program before giving it a type.
- Keep assertions small and close to the reason they are true.
- Add a comment stating why the assertion holds.
- Treat
!andas unknown as Tas items to review.
Exercise
The code const n = JSON.parse("\"7\"") as number; console.log(n + 1); compiles without errors. What does it print, and why does the assertion not prevent the problem?
Show answer
It prints "71". JSON.parse returns the string "7", and the assertion only changes what the compiler believes, not the value. Since n is really a string, + concatenates. To fix it, parse into unknown, check typeof, and convert with Number if needed.
Exercise
Why does const c = { host: "x" } as Config; compile when Config requires a port property, while const c: Config = { host: "x" }; does not? Which should you use to check the object?
Show answer
The annotation checks that the object literal fully matches Config, so the missing port is an error. The assertion only requires the two types to overlap, and the literal's type is a supertype of Config, so it is accepted. Use the annotation (or satisfies) when you want the compiler to verify the shape.