#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 36 of 48medium

What are Type Predicates?

Custom type guard functions.

What You'll Learn

  • Type predicate syntax
  • Creating custom guards
  • Practical examples

Type Predicate Syntax

code.tsTypeScript
function isString(value: unknown): value is string {
  return typeof value === "string";
}

How It Works

code.tsTypeScript
function processValue(value: string | number) {
  if (isString(value)) {
    // TypeScript knows value is string
    console.log(value.toUpperCase());
  } else {
    // TypeScript knows value is number
    console.log(value.toFixed(2));
  }
}

Checking Object Types

code.tsTypeScript
interface User {
  name: string;
  email: string;
}

interface Admin {
  name: string;
  role: string;
}

function isAdmin(user: User | Admin): user is Admin {
  return "role" in user;
}

function greet(user: User | Admin) {
  if (isAdmin(user)) {
    console.log(`Admin: ${user.role}`);
  } else {
    console.log(`User: ${user.email}`);
  }
}

Array Filtering

code.tsTypeScript
function isNotNull<T>(value: T | null): value is T {
  return value !== null;
}

const values = [1, null, 2, null, 3];
const numbers = values.filter(isNotNull);
// Type: number[] (not (number | null)[])