TypeScript Snippet

isDefined Type Guard

Difficulty: Easy

Filtering an array of `(T | undefined)[]` should leave you with `T[]`, but `Array.prototype.filter(Boolean)` leaves the type as `(T | undefined)[]` because the compiler does not understand the predicate. A user-defined type guard with the `value is T` return type fixes the inference. This snippet covers the basic `isDefined`, an `isNonNullable` variant that also drops `null`, and a generic `compact` that uses the guard to narrow at the array level.

Code Snippets
/

isDefined Type Guard

isDefined Type Guard

Filtering an array of `(T | undefined)[]` should leave you with `T[]`, but `Array.prototype.filter(Boolean)` leaves the type as `(T | undefined)[]` because the compiler does not understand the predicate. A user-defined type guard with the `value is T` return type fixes the inference. This snippet covers the basic `isDefined`, an `isNonNullable` variant that also drops `null`, and a generic `compact` that uses the guard to narrow at the array level.

TypeScript
Easy
3 snippets
ts-type-guards
ts-type-narrowing
utility
code-template

916 views

6

The value is T predicate is the magic clause: when isDefined(value) returns true, TypeScript narrows the variable's type from T | undefined to T in every downstream branch and in Array.prototype.filter. Without the predicate, filter keeps the input element type, so the output is still (string | undefined)[]. The function body is just a runtime check (value !== undefined); the predicate type is what tells the compiler the runtime check is sound. This is the smallest reusable type guard you should ship in every TypeScript codebase.