Type Guard Toolkit
What you'll build
A set of type guard functions (isString, isNumber, isObject, isArray, isInstanceOf) that use the `x is T` predicate for automatic type narrowing.
Goals
- Write user-defined type guards with `is` predicate
- Combine type guards for complex types
- Narrow union types safely at runtime
- Build a reusable validation toolkit
Prerequisites
- Type guards
- Union types
- typeof and instanceof
Steps
- 1
Write primitive type guards
Create type guards for primitives using typeof. The return type
x is Ttells TypeScript to narrow the type when the guard returns true.Codefunction isString(x: unknown): x is string { return typeof x === "string"; } function isNumber(x: unknown): x is number { return typeof x === "number"; } function isBoolean(x: unknown): x is boolean { return typeof x === "boolean"; }Expected result
Three type guards. After isString(x) returns true, x is narrowed to string.
- 2
Write object and array guards
Create guards for objects and arrays. For arrays, check Array.isArray. For objects, verify typeof and null exclusion.
Codefunction isObject(x: unknown): x is Record<string, unknown> { return typeof x === "object" && x !== null && !Array.isArray(x); } function isArray(x: unknown): x is unknown[] { return Array.isArray(x); }Expected result
Object and array type guards that properly narrow types.
- 3
Build a combined validator
Use the type guards together to validate unknown data and narrow it to a specific shape. This pattern is common when parsing JSON.
Codefunction parseUser(data: unknown): { name: string; age: number } | null { if (!isObject(data)) return null; if (!isString(data.name)) return null; if (!isNumber(data.age)) return null; return { name: data.name, age: data.age }; }Expected result
A function that validates unknown data and returns a typed object or null.
- 4
Add type guards & runtime checks
Write a user-defined type guard function to validate data shape at runtime, combined with the unknown type to safely handle external input. Type guards give TypeScript runtime type safety too.
Codetype User = { id: number; name: string }; function isUser(value: unknown): value is User { if (typeof value !== "object" || value === null) return false; const obj = value as Record<string, unknown>; return typeof obj.id === "number" && typeof obj.name === "string"; } // Usage with unknown input const data: unknown = JSON.parse(rawJson); if (isUser(data)) { console.log(data.name); // TS knows data is User here } else { console.error("Invalid user data"); }Expected result
When isUser returns true, TS narrows data to User type; invalid data goes to the else branch.
- 5
Add generic utility functions
Write generic utility functions (e.g., deepFreeze, groupBy) to enhance type-safe reuse. Generics let utility functions work with multiple types without losing type information.
Codefunction groupBy<T, K extends string | number>( items: T[], keyFn: (item: T) => K ): Record<K, T[]> { const result = {} as Record<K, T[]>; for (const item of items) { const key = keyFn(item); (result[key] ??= []).push(item); } return result; } // Usage const byAge = groupBy(users, u => u.age);Expected result
groupBy groups any array by key, returning a type-safe Record.
Try it yourself
What you learned
You built reusable type guards that narrow types at runtime. The x is T predicate is the key — it bridges runtime checks to compile-time type safety, enabling TypeScript to narrow types inside if blocks automatically.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.