Sub topic 6
Type assertions: when as is and is not safe
This chapter assumes you know TypeScript annotations, interfaces and union types. You should also know how unknown and narrowing with typeof, instanceof and in work, and how to run tsc or use an editor that reports type errors.
A type assertion tells the compiler to treat a value as a type you name. Used well, it records a fact the compiler cannot work out. Used badly, it turns a type error into a runtime crash. This chapter covers how assertions work, which ones are safe, and what to use instead when they are not.
What an assertion does
The as operator changes what the compiler believes about an expression. It does not change the value, and it does not check anything when the program runs. After compilation, the assertion is erased.
const input: unknown = "hello";
const text = input as string;
console.log(text.toUpperCase()); // HELLOHere the assertion is correct, so nothing goes wrong. If input held a number, the compiler would still accept the code, and text.toUpperCase() would throw at runtime. The compiler trusts you completely.
Other languages call this operation a cast, and a cast there often converts the value or checks it. In TypeScript, as does neither.
There is an older angle-bracket form, <string>input. It means the same thing, but it conflicts with JSX syntax in .tsx files, so most codebases use as.
What the compiler allows
The compiler does not accept every assertion. It requires the source type and the target type to overlap: one must be assignable to the other. This blocks obvious mistakes.
const n = 5;
// const s = n as string;
// error: Conversion of type 'number' to type 'string' may be a mistakeTwo types are exempt from this rule. A value of type unknown or any can be asserted to any type. This is why asserting unknown is so tempting and so dangerous: the compiler's only safeguard is gone.
If you must force an assertion between unrelated types, you can go through unknown first. This is called a double assertion.
const n = 5;
const s = n as unknown as string; // compiles
console.log(s.toUpperCase()); // TypeError: s.toUpperCase is not a functionA double assertion is a signal that the types disagree with reality. Treat it as a code smell and look for the cause.
Assertions that are usually safe
An assertion is safe when you have information the compiler cannot see, and that information is stable. Four cases come up often.
- Narrowing a broad DOM type.
querySelectorreturnsElement | null. If your markup guarantees an input exists, you can assert it. This needs thedomlibrary in yourtsconfig.json. - Const assertions.
as constasks the compiler for the narrowest type. It makes no claim the compiler could not verify. - Non-null assertions. The postfix
!removesnullandundefinedfrom a type. - Asserting after a real check. If you validated the value yourself in a way the compiler cannot follow, an assertion records that fact.
const email = document.querySelector("#email") as HTMLInputElement;
console.log(email.value);
const config = { mode: "dark", retries: 3 } as const;
// config.mode has type "dark", and the properties are readonly
const stock = new Map<string, number>([["apple", 3]]);
const apples = stock.get("apple")!; // number
const pears = stock.get("pear")!; // also typed number, but undefined at runtime
console.log(apples.toFixed(), pears.toFixed()); // TypeError on pearsThe first two uses are low risk. as const is a different kind of assertion, because the compiler checks it and it only narrows. The querySelector assertion depends on your HTML, so if someone edits the markup, the compiler will not notice.
The ! operator is the riskiest of the four. In the example, get("pear") returns undefined, but the assertion hid that from the compiler. Prefer an explicit check unless the invariant is local and obvious.
Assertions that lie
The worst use is asserting data from outside your program, such as parsed JSON or an API response, to an interface.
interface User {
name: string;
age: number;
}
const raw: unknown = JSON.parse('{"name":"Ada"}');
const user = raw as User; // compiles
console.log(user.age.toFixed(2));
// TypeError: Cannot read properties of undefined (reading 'toFixed')The type User now claims that age is a number, but nothing verified it. The crash happens far from the cause, and the type annotations make the code look safe to every reader.
A second problem is that downcasting hides missing properties. An annotation forces an object to match its type, but an assertion does not.
interface User {
name: string;
age: number;
}
// const a: User = {}; // error: missing 'name' and 'age'
const b = {} as User; // compiles: User is assignable to {}
const c = { name: "Ada" } as User; // compiles, but age is missingIn both cases the compiler reasons that User is assignable to the literal's type, so the two types overlap and the assertion is allowed.
Annotation, assertion, and satisfies
Three tools look similar but behave differently. satisfies needs TypeScript 4.9 or later.
| Form | Checks the value against T? | Type of the expression | Missing properties |
|---|---|---|---|
| `const x: T = v` | Yes | `T` | Error |
| `const x = v as T` | Only that the types overlap | `T` | Allowed |
| `const x = v satisfies T` | Yes | The inferred type of `v` | Error |
When you only want to verify that a literal matches a type, use satisfies or an annotation. Reach for as only when you are telling the compiler something it cannot check.
interface Options {
retries: number;
verbose?: boolean;
}
const options = { retries: 3 } satisfies Options;
console.log(options.retries.toFixed()); // retries is known to be number
// const bad = { retries: "3" } satisfies Options; // errorReplacing assertions with checks
If a value comes from outside the program, validate it. Chapter material you have already seen applies here: a user-defined type guard returns a boolean and narrows inside an if. An assertion function does the same job but throws on failure, so the code after the call is narrowed.
interface User {
name: string;
age: number;
}
function assertIsUser(value: unknown): asserts value is User {
if (
typeof value !== "object" ||
value === null ||
!("name" in value) ||
typeof value.name !== "string" ||
!("age" in value) ||
typeof value.age !== "number"
) {
throw new TypeError("Value is not a User");
}
}
const raw: unknown = JSON.parse('{"name":"Ada","age":36}');
assertIsUser(raw);
console.log(raw.name.toUpperCase()); // raw is User from here onProperties like value.name are narrowed through in checks, which needs TypeScript 4.9 or later. The name asserts value is User is a signature, and it is still a promise. If the body of assertIsUser is wrong, the compiler believes it anyway. Keep these functions short and test them, because they are the only thing standing between the data and the type.
The checks in the function body run when the program runs. That is the difference from as: a failed check throws immediately and close to the source, with a clear message.
Deciding when to assert
Some practical rules follow from this.
- Never assert the result of
JSON.parse,fetch(...).json()or acatchvariable directly to a domain type. - Keep each assertion as close as possible to the fact that justifies it, and comment on that fact.
- Prefer asserting to a wider or equal type over asserting to a narrower one. Widening is always safe, and a narrowing assertion is a claim.
- Avoid
as any. It discards all checking for the expression, and theanyspreads to whatever it touches. - Search for
as unknown asduring code review. Each match deserves a justification.
Assertions drift over time
An assertion is true when you write it and can become false later. Suppose you assert a value to a type and later someone changes the producer of that value. The compiler cannot flag the assertion as wrong, because it was never checking. A runtime check will fail loudly in this situation, and an assertion will fail silently.
Because of this, treat assertions as debt. Each one should have a reason that a reviewer can verify without running the code. When you find yourself writing the same assertion repeatedly, wrap the check in one function with a real runtime test and call that instead.
Summary of the rules
as Tchanges only the compile-time type and is erased at runtime.- The compiler allows
aswhen the types overlap, and always allows it fromunknownorany. - Assertions are reasonable for DOM lookups,
as const, and facts you control locally. - Assertions are unsafe for external data, and for
!on values that may truly be missing. - A type guard or assertion function checks at runtime. Prefer these for data you did not create.
Exercise
The code const u = { name: "Ada" } as User; compiles even though User also requires an age: number. Why does the compiler accept it, and what would you write instead if you wanted the compiler to report the missing property?
Show answer
The compiler accepts it because User is assignable to the literal's type { name: string }, so the two types overlap and the assertion is allowed. Assertions do not check that every required property is present. To get an error, use an annotation (const u: User = { name: "Ada" };) or satisfies User, both of which check the value against User and report the missing age.
Exercise
A function receives body: unknown from an HTTP request and currently does const order = body as Order;, where Order has id: string and total: number. Rewrite the conversion so a malformed body throws a TypeError with a clear message, and explain why this is safer than the assertion.
Show answer
Write an assertion function that checks the shape at runtime and then call it:
function assertIsOrder(value: unknown): asserts value is Order {
if (
typeof value !== "object" || value === null ||
!("id" in value) || typeof value.id !== "string" ||
!("total" in value) || typeof value.total !== "number"
) {
throw new TypeError("Body is not a valid Order");
}
}
assertIsOrder(body);
// body is now Order
It is safer because the shape is verified when the program runs, so a bad body fails immediately with a clear error. The as Order version would compile and then fail later, at the point where a missing field is used.