Skip to content
Guest
Learn TypeScript · Course Syllabus Show lessons
Advanced TypeScript · 8 min read · Intermediate

Custom Type Guards & Predicates

Write reusable narrowing functions with `val is Type` return predicates so TypeScript narrows unknown inputs safely.

What you'll learn

  • Write custom type guard functions returning `value is Type`
  • Filter arrays cleanly without leaving undefined in the resulting type
  • Narrow unknown JSON payloads before accessing properties

When typeof or instanceof is not enough, a custom type guard (function isUser(x: unknown): x is User) teaches the TypeScript compiler how to narrow an arbitrary value inside if (isUser(data)) or items.filter(isDefined).

Fill-in-the-Blank Exercise

Type Predicate Return Type

Write a type predicate so TypeScript narrows val to string.

function isNonEmpty(val: unknown): val   {
return typeof val === "string" && val.length > 0;
}

Live Code Lab

TypeScripttype_guards.ts
Expected OutputClick “Run Live” to compile with TypeScript 5.6
Defined tracks: TS, React, Node

Check Your Understanding

Score: 0 / 1

1. What does the return annotation `x is User` tell the TypeScript compiler?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind