Lesson 5 of 7
User-Defined Type Guards
When built-in narrowing (typeof, instanceof, in) is insufficient - for example, validating runtime API data - you write a type guard function. A type guard uses the `is` return type to tell TypeScript that if the function returns `true`, the parameter has a specific type.
Type Guards - is, asserts, and Assertion Functions
// ── User-defined type guard - is keyword ─────────────────────
// Returns a type predicate: "if this returns true, value IS Task"
function isTask(value: unknown): value is Task {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
"title" in value &&
"status" in value
);
}
const raw: unknown = await fetchFromApi("/tasks/1");
if (isTask(raw)) {
console.log(raw.title); // ✅ TypeScript trusts the guard
}
// ── Array type guard ──────────────────────────────────────────
function isTaskArray(value: unknown): value is Task[] {
return Array.isArray(value) && value.every(isTask);
}
// ── Narrowing with filter ─────────────────────────────────────
const items: (Task | null)[] = [task1, null, task2, null];
// Without guard - filter(Boolean) returns (Task | null)[] still
const withNulls = items.filter(Boolean); // type: (Task | null)[]
// With guard - correct narrow to Task[]
function isNotNull<T>(value: T | null | undefined): value is T {
return value !== null && value !== undefined;
}
const noNulls = items.filter(isNotNull); // type: Task[]
// ── Assertion function - asserts keyword ─────────────────────
// Throws if condition fails, narrows if it passes:
function assertIsString(val: unknown): asserts val is string {
if (typeof val !== "string") {
throw new TypeError(`Expected string, got ${typeof val}`);
}
}
// assertIsTask - useful for internal validation
function assertIsTask(val: unknown): asserts val is Task {
if (!isTask(val)) {
throw new Error("Expected a Task object");
}
}
// Usage - after the assertion, TypeScript narrows automatically:
const payload: unknown = JSON.parse(rawInput);
assertIsTask(payload);
console.log(payload.title); // ✅ typed as Task
// ── Type guard for discriminated union ───────────────────────
type SuccessResponse<T> = { status: "ok"; data: T };
type ErrorResponse = { status: "error"; message: string };
type ApiResult<T> = SuccessResponse<T> | ErrorResponse;
function isSuccess<T>(result: ApiResult<T>): result is SuccessResponse<T> {
return result.status === "ok";
}
const result = await fetchTask(1);
if (isSuccess(result)) {
console.log(result.data.title); // ✅
} else {
console.error(result.message); // ✅
}Common Mistakes
- Type guards don't do runtime validation - a type guard TELLS TypeScript the type; it doesn't automatically verify all properties. A badly-written guard (`return true`) will lie to TypeScript and cause runtime errors. Always validate thoroughly inside the guard.
- Using `as` instead of guards for API data - casting API responses with `as` bypasses all type checking. The API could return anything. Use a real guard or Zod to validate.
- Forgetting the filter pattern - `.filter((x): x is T => x !== null)` is the idiomatic way to remove nulls from an array and have TypeScript know the result is `T[]`. Without the type predicate return type, TypeScript won't narrow.
Tip
Tip
Practice UserDefined Type Guards in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for User-Defined Type Guards
Practice Task
Note
Practice Task - (1) Write a working example of UserDefined Type Guards from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with UserDefined Type Guards is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- When built-in narrowing (typeof, instanceof, in) is insufficient - for example, validating runtime API data - you write a type guard function.
- Type guards don't do runtime validation - a type guard TELLS TypeScript the type; it doesn't automatically verify all properties. A badly-written guard (`return true`) will lie to TypeScript and cause runtime errors. Always validate thoroughly inside the guard.
- Using `as` instead of guards for API data - casting API responses with `as` bypasses all type checking. The API could return anything. Use a real guard or Zod to validate.
- Forgetting the filter pattern - `.filter((x): x is T => x !== null)` is the idiomatic way to remove nulls from an array and have TypeScript know the result is `T[]`. Without the type predicate return type, TypeScript won't narrow.
Finished this lesson?