Sub topic 6
Type Assertions: When `as` Is and Is Not Safe
Prerequisites and the core idea
This chapter assumes you know TypeScript annotations, interfaces, union types, and basic JavaScript checks such as typeof and instanceof.
A type assertion tells the TypeScript compiler to treat a value as a particular type. It uses the as keyword:
const value = "hello" as string;The assertion changes the compiler's view of value. It does not change the value at runtime and does not check whether the value really is a string.
This distinction matters most when data comes from outside your program. JSON, API responses, DOM elements, and JavaScript libraries can contain values that do not match your TypeScript types.
Assertions do not validate values
Consider this code:
interface User {
name: string;
age: number;
}
const input: unknown = JSON.parse('{"name":"Ada"}');
const user = input as User;
console.log(user.name);
console.log(user.age.toFixed());The assertion makes user.age.toFixed() compile. However, the parsed object has no age property. The program throws a TypeError when it tries to call toFixed.
| Technique | Checks at runtime | Changes the value | Main risk |
|---|---|---|---|
| `value as User` | No | No | A false claim can cause a runtime error |
| `typeof value === "string"` | Yes | No | A basic check may be incomplete |
| `isUser(value)` | Yes | No | The guard can be incorrectly written |
| `User` interface | No | No | Interfaces disappear when code runs |
Treat an assertion as a promise that your code must already have justified. It is not a replacement for validation.
The safe pattern: validate, then use
A type guard is a function whose return type has the form value is SomeType. The function checks a value at runtime. If it returns true, TypeScript narrows the value inside that branch.
interface User {
name: string;
age: number;
}
function isUser(value: unknown): value is User {
if (typeof value !== "object" || value === null) {
return false;
}
if (!("name" in value) || !("age" in value)) {
return false;
}
return (
typeof value.name === "string" &&
typeof value.age === "number"
);
}
function describeUser(value: unknown): string {
if (!isUser(value)) {
return "Invalid user data";
}
return `${value.name} is ${value.age} years old`;
}
const parsed: unknown = JSON.parse('{"name":"Ada","age":36}');
console.log(describeUser(parsed));The unknown type prevents property access before validation. The guard supplies the runtime evidence that the assertion alone would lack.
When an assertion is reasonable
Assertions are useful when TypeScript cannot infer information that you know from a reliable source.
For example, a DOM lookup may return Element | null, while your code knows that a specific element is an input:
const element = document.querySelector("#email");
if (element === null) {
throw new Error("Email field is missing");
}
const emailInput = element as HTMLInputElement;
console.log(emailInput.value);This assertion is reasonable only if the HTML contract guarantees that #email identifies an <input>. If that contract can change, check the element instead:
if (!(element instanceof HTMLInputElement)) {
throw new Error("Expected an input element");
}
console.log(element.value);Prefer a runtime check when data can be malformed, changed by another system, or controlled by a user.
Assertions through `unknown`
TypeScript may reject a direct assertion between unrelated types:
const count = 42;
// const text = count as string; // usually rejectedWriting count as unknown as string can force the assertion through:
const text = count as unknown as string;This does not make the value safe. It only bypasses another compiler check. Use this pattern only at a narrow boundary with a documented invariant, and avoid using it to silence an error you have not investigated.
Exercise
Exercise
Why is const user = data as User unsafe when data comes from JSON, and what should you do instead?
Show answer
The assertion performs no runtime validation. Parse the value as unknown, validate its required fields with a type guard or validation library, and use it as User only after the check succeeds.