Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 96 ยท Narrowing

Custom Type Guards

Write your own TypeScript type guards - type predicates (x is T), validating unknown JSON, assertion functions, inferred predicates and schema libraries.

The built-in checks from Narrowing (typeof, in, instanceof, equality) cover a lot, but not everything. How do you check that an unknown value parsed from JSON is really a User? How do you filter null out of an array and get string[] back instead of (string | null)[]? For that, you write a custom type guard: an ordinary function whose return type tells TypeScript what a true result proves.

There are two kinds. A type predicate function returns a boolean and has the return type value is T; an if around the call narrows. An assertion function returns nothing, throws when the check fails, and has the return type asserts value is T; the code after the call is narrowed. This lesson shows both, how to use them to validate untrusted data, and how to avoid guards that lie. The function-level syntax was introduced in this, Parameter Destructuring and Type Predicates; here we put it to work.

Type predicates: value is T

A function that returns boolean tells TypeScript nothing about its argument, even if its body checks everything carefully. Change the return type to a type predicate and the result becomes a narrowing check, just like typeof:

TypeScript A boolean function vs a type predicate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The syntax is parameterName is Type, where the parameter name must match one of the function's parameters and Type must be assignable to that parameter's type. When the function returns true, the argument is narrowed to Book. When it returns false, it's narrowed to everything else in the union, here Movie.

If you used looksLikeBook in the if instead, item.pages would be error TS2339, because TypeScript has no idea what the boolean means.

Guards that make filter() precise

The most common use of a type predicate is Array.prototype.filter. Its type definitions include an overload that accepts a type predicate and returns a narrower array:

TypeScript Filtering out null and undefined

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

isDefined is a small generic helper you'll find in many code bases: for any T, a true result proves the value is NonNullable<T>, which is T without null and undefined (see Built-in Utility Types). Note that 0 survives, because the check compares with null/undefined instead of testing truthiness.

The second half shows inferred type predicates, added in TypeScript 5.5. When a function returns a boolean expression that narrows its parameter, and the narrowing is exact both ways, TypeScript infers n is string by itself. It doesn't fire for truthiness checks like (n) => !!n, because a false result wouldn't prove the value is null (it could be ''). When in doubt, hover the function or write the predicate yourself.

Validating unknown data

Types are erased at runtime, so anything that enters your program from outside (parsed JSON, process.argv, files, a message from a worker) is really unknown. JSON.parse returns any, which is worse: it switches checking off. The safe pattern is: treat the input as unknown, check it with a guard, and only then use it.

TypeScript A guard for parsed JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

A few techniques make this readable:

  • Small, reusable guards (isRecord, isStringArray) compose into bigger ones.
  • isRecord narrows to Record<string, unknown>, so value.id is allowed and has type unknown, which you then check with typeof. Nothing is ever any.
  • const data: unknown = JSON.parse(json); deliberately throws away the any. That one annotation is the most valuable line in the example.
  • Arrays need Array.isArray plus a check of every element. typeof [] === 'object', so isRecord excludes arrays explicitly.

TypeScript trusts a type predicate completely. It never checks that your function body proves what the return type claims. function isUser(v: unknown): v is User { return true; } compiles, and every caller will treat garbage as a User. Keep guards small, test them, and update them whenever the type changes.

Assertion functions: asserts value is T

Sometimes a failed check isn't something to handle, it's a bug or bad input that should stop everything. An assertion function checks a condition and throws if it's false. Its return type asserts value is T tells TypeScript that if the function returns at all, the value is a T:

TypeScript Assertion functions narrow the code after them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

There are two forms:

  • asserts value is T narrows the parameter to T, like a predicate that throws instead of returning false.
  • asserts condition narrows according to whatever expression you pass. assert(config.port !== undefined, ...) works just like an if that throws, so config.port is a number afterwards. Node's node:assert module exports functions typed exactly like this.

Assertion functions must return void, and the call has to be a statement on its own (not part of an expression).

The explicit annotation rule

There's one quirk you'll hit sooner or later. When the assertion function is an arrow function stored in a variable, TypeScript can only use it for narrowing if the variable has an explicit type annotation:

TypeScript Assertion arrow functions need annotations (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The call fails with error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. Because the assertion was ignored, input is still unknown on the next line, which adds a second error, TS18046: 'input' is of type 'unknown'. The fix is either a function declaration (always fine) or an annotated variable:

TypeScript
type AssertNumber = (value: unknown) => asserts value is number;

const assertNumber: AssertNumber = (value) => {
  if (typeof value !== 'number') {
    throw new TypeError('not a number');
  }
};

The same rule applies to assertion methods called through an object: every name in validator.check(x) needs a declared type, so even a class instance must be declared as const validator: Validator = new Validator(); (inside the class, this.check(x) works without extra annotations).

Predicates as methods: this is T

A class method can narrow the object it's called on with a this is T predicate. This is handy for class hierarchies (more in Inheritance and Abstract Classes):

TypeScript this-based type guards

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Inside the if, node is a Folder, so node.children is allowed. You could write node instanceof Folder directly, of course; the method form shines when the check is more involved or when callers shouldn't need to know the subclass.

Schema libraries: guards without the boilerplate

Hand-written guards get long for big types, and keeping them in sync with the interface is a chore. In real projects, most teams use a schema validation library such as Zod, Valibot or ArkType. You describe the shape once, as a runtime value, and the library gives you both a validator and the static type. These are npm packages, so they can't run in our editor, but here's what Zod code looks like:

TypeScript
import { z } from 'zod';

const UserSchema = z.object({
  id: z.number().int(),
  name: z.string().min(1),
  email: z.string().email().optional(),
  roles: z.array(z.string()),
});

// The static type is derived from the schema: no duplicate interface.
type User = z.infer<typeof UserSchema>;

const result = UserSchema.safeParse(JSON.parse(body));
if (result.success) {
  console.log(result.data.name); // result.data: User
} else {
  console.log(result.error.issues); // detailed messages per field
}

safeParse returns a discriminated union on success, so the usual narrowing applies. Libraries like this also report why data was rejected, which a boolean guard can't. Writing your own guards is still worth knowing: for a handful of small types it's often simpler than adding a dependency, and it's exactly what these libraries do internally. Typing APIs and JSON Data goes further.

Choosing the right tool

You want to... Use
Branch on what a value is A type predicate: function isX(v): v is X
Stop with an error if a value is wrong An assertion function: asserts v is X
Check a condition and narrow after it asserts condition
Remove null/undefined from an array filter(isDefined) or an inferred predicate (TS 5.5+)
Validate large external payloads A schema library (Zod, Valibot)
Silence the compiler without checking Nothing! A type assertion (as User) checks nothing at runtime

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the return type of a function that narrows its parameter x to Date when it returns true?

    A type predicate x is Date is a boolean return type that also tells TypeScript what true proves. asserts x is Date is for functions that throw instead.
  2. 2. function isUser(v: unknown): v is User { return true; } What does TypeScript do?

    TypeScript never verifies that a guard's body matches its predicate. A wrong guard is as dangerous as an unchecked as cast.
  3. 3. After assert(user.age !== undefined, 'age missing'); where assert has the return type asserts condition, what is the type of user.age (declared age?: number)?

    asserts condition narrows as if the condition were checked in an if that throws, so undefined is removed.
  4. 4. Why is const data: unknown = JSON.parse(text); better than const data = JSON.parse(text);?

    any disables checking, so every property access would compile. unknown makes every use an error until a guard narrows it.
  5. 5. const assertOk = (v: unknown): asserts v is string => { ... } is called as assertOk(x);. What happens?

    For an assertion stored in a variable, the variable itself needs a declared type, e.g. const assertOk: AssertString = ..., or use a function declaration.

Summary

  • A type predicate (value is T) turns a boolean function into a narrowing check; true narrows to T, false to the rest of the union.
  • Predicates make filter precise: filter(isDefined) gives T[] without null. TypeScript 5.5+ infers simple predicates such as (n) => n !== null.
  • Validate external data by typing it unknown and composing small guards (isRecord, isStringArray, then isUser).
  • TypeScript trusts guards blindly, so keep them small, correct and tested.
  • Assertion functions (asserts value is T, asserts condition) throw on failure and narrow the code after the call. Arrow-function assertions need an explicit variable type (TS2775).
  • Methods can narrow this with this is T. For large payloads, schema libraries such as Zod derive the type and the validator from one definition.

Next: Object Types in Depth