0Pricing
TypeScript Academy · Lesson

User-Defined Type Guard Functions

Write is predicates to create custom type guards.

User-Defined Type Guard Functions is a free TypeScript Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Welcome

User-defined type guards let you encapsulate a narrowing check into a reusable function using the `is` predicate return type.

The is Predicate Return Type

A type guard function returns `paramName is Type`. When the function returns true, TypeScript narrows the parameter to that type.
function isString(val: unknown): val is string {
  return typeof val === 'string';
}

Using a Type Guard

Call the type guard in an if condition. TypeScript narrows the type inside the block.
function process(val: unknown) {
  if (isString(val)) {
    console.log(val.toUpperCase()); // val: string
  }
}

Type Guard for Interfaces

Since you can't use instanceof with interfaces, type guards are the primary way to narrow interface unions.
interface Cat { meow(): void }
interface Dog { bark(): void }
function isCat(pet: Cat | Dog): pet is Cat {
  return 'meow' in pet;
}

Type Guards for Complex Objects

Write a type guard that validates an object's shape at runtime before using it as a specific type.
interface User { name: string; age: number; }
function isUser(val: unknown): val is User {
  return (
    typeof val === 'object' &&
    val !== null &&
    typeof (val as any).name === 'string' &&
    typeof (val as any).age === 'number'
  );
}

Type Guards vs Assertions

Type guards check at runtime. Type assertions (as Type) are compile-time only and can lie. Prefer guards for external data.

Array.isArray as a Type Guard

Array.isArray is a built-in type guard. TypeScript understands it and narrows accordingly.
function flatten(val: string | string[]): string[] {
  return Array.isArray(val) ? val : [val];
}

Generic Type Guards

Type guards can be generic for reusable runtime checkers.
function isNonNull<T>(val: T | null | undefined): val is T {
  return val !== null && val !== undefined;
}
const values = [1, null, 2, undefined].filter(isNonNull);
// values: number[]

Assertion Functions

Assertion functions (using asserts) throw if the condition is false and narrow the type after the call.
function assertIsString(val: unknown): asserts val is string {
  if (typeof val !== 'string') throw new TypeError('Not a string');
}
assertIsString(input);
console.log(input.toUpperCase()); // narrowed to string

The Responsibility of Type Guards

TypeScript trusts type guard return values completely. If your guard is wrong, TypeScript will not detect the mismatch at compile time.

Type Guards in filter and find

Pass type guards directly to array.filter to narrow the result type.
const mixed: (string | null)[] = ['a', null, 'b'];
const strings = mixed.filter((x): x is string => x !== null);
// strings: string[]

Quick Check

What return type annotation marks a function as a TypeScript type guard?

Recap

User-defined type guards use `param is Type` return types to encapsulate narrowing logic. They work with filter/find, enable interface narrowing, and can be made generic. Assertion functions narrow without returning a boolean.

Frequently asked questions

Is the “User-Defined Type Guard Functions” lesson free?

Yes — the full text of “User-Defined Type Guard Functions” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “User-Defined Type Guard Functions”?

Write is predicates to create custom type guards. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “User-Defined Type Guard Functions” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. typeof and Truthiness Narrowing
  2. instanceof and in Narrowing
  3. User-Defined Type Guard Functions
  4. Exhaustiveness Checking with never
← Back to TypeScript Academy