Sub topic 2
Writing User-Defined Type Guards
Assume basic TypeScript types, union types, typeof, instanceof, and try/catch. This chapter focuses on checking values at runtime while keeping TypeScript's static types accurate.
Writing user-defined type guards
A user-defined type guard is a function whose return type uses value is Type. It checks an unknown value and tells the compiler which type is safe inside a conditional block.
interface User {
name: string;
age: number;
}
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"name" in value &&
typeof value.name === "string" &&
"age" in value &&
typeof value.age === "number"
);
}
const value: unknown = { name: "Ada", age: 36 };
if (isUser(value)) {
console.log(value.name.toUpperCase());
}The checks must match the claim. A guard that checks only name should not claim that the value is a complete User.
Type assertions: when `as` is and is not safe
A type assertion, such as value as User, changes the compiler's view without checking the value at runtime. Use one only when another trusted operation already proved the shape.
Prefer a guard for API responses, file contents, and other untrusted data.
Compiler options that surface `any` and `unknown`
Strict settings expose unsafe assumptions early.
| Option | Effect |
|---|---|
| `noImplicitAny` | Reports parameters and variables that would otherwise become implicit `any`. |
| `useUnknownInCatchVariables` | Types caught errors as `unknown`, requiring a check before reading properties. |
Enable them through strict or explicitly:
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"useUnknownInCatchVariables": true
}
}Handling JSON and caught errors
JSON.parse can produce any runtime value. Treat its result as unknown, validate it, and handle non-Error thrown values.
try {
const data: unknown = JSON.parse(input);
if (isUser(data)) {
console.log(data.age);
}
} catch (error: unknown) {
console.error(error instanceof Error ? error.message : String(error));
}Containing `any`
Use ESLint rules such as @typescript-eslint/no-explicit-any and @typescript-eslint/no-unsafe-assignment. During migration, isolate unavoidable any at a small boundary, convert it to unknown, and validate it immediately.
Exercise
Why is unknown safer than any for an API response?
Show answer
unknown requires a runtime check before property access or a function call; any allows unchecked operations.