Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. TypeScript Dictionary
  3. User-Defined Type Guard is

User-Defined Type Guard is

Since: TypeScript 1.0(2014)

A user-defined type guard is a mechanism for extracting type-narrowing logic into a standalone function. By specifying a type predicate in the form x is T as the return type, TypeScript narrows the type when you use that function in a conditional expression.

Syntax

function isT(x: unknown): x is T {
  // Actual validation logic (must return a boolean)
  return /* ... */;
}

Sample Code

interface User {
  id: number;
  name: string;
}

function isUser(value: unknown): value is User {
  return (
    typeof value === 'object' &&
    value !== null &&
    typeof (value as User).id === 'number' &&
    typeof (value as User).name === 'string'
  );
}

const data: unknown = { id: 1, name: 'Ryomen Sukuna' };

if (isUser(data)) {
  // Inside this block, data is narrowed to: User
  console.log(data.name);
}

// Combining with array filtering
const values: (string | null | undefined)[] = ['a', null, 'b', undefined, 'c'];

function isString(v: unknown): v is string {
  return typeof v === 'string';
}

const strings: string[] = values.filter(isString);
// => ['a', 'b', 'c']  (typed as string[])

// Applying to discriminated unions
type Circle = { kind: 'circle'; radius: number };
type Square = { kind: 'square'; side: number };
type Shape = Circle | Square;

function isCircle(shape: Shape): shape is Circle {
  return shape.kind === 'circle';
}

Running the above produces the following output:

npx ts-node ts_is_guard.ts
Ryomen Sukuna

Notes

Using a type predicate (x is T) lets you extract complex validation logic into a function while still benefiting from TypeScript's type narrowing. The parameter name in the predicate must match the corresponding parameter name in the function signature.

One important caveat: TypeScript does not report a compile error if the implementation of a type guard function is incorrect. You are responsible for writing accurate validation logic. For example, simply writing return true will pass the type checker without any error, so it is essential to implement the actual validation correctly.

When you pass a type guard function to the array filter method, the type of the resulting array is narrowed accordingly. This is especially useful for cases like obtaining a string[] from a (string | null)[].

If you find any errors or copyright issues, please .