Course contentsShow
← TypeScript
Lesson 227 of 1,7965. Type Narrowing FundamentalsFree lesson

Generic Type Predicates

Creating reusable type guards with generics to narrow various types with a single function.

Generic Type Predicates

What you'll learn: How to write a single type guard function that works for multiple types using generics.

The Reusability Problem

You've learned to write type predicates for specific types — functions that return value is SomeType. But what if you need similar narrowing logic for many different types? Writing separate type guards for each would mean repeating yourself constantly.

Creating Generic Type Guards

Generic type predicates let you parameterize the type being checked, making one function work across many scenarios:

function isNonNull<T>(value: T | null): value is T {
  return value !== null;
}

const maybeString: string | null = "hello";
const maybeNumber: number | null = 42;

if (isNonNull(maybeString)) {
  // TypeScript knows: maybeString is string
  console.log(maybeString.toUpperCase());
}

if (isNonNull(maybeNumber)) {
  // TypeScript knows: maybeNumber is number
  console.log(maybeNumber.toFixed(2));
}

The <T> makes this function generic. The predicate value is T means "if this returns true, the value is whatever type T represents in this specific call."

The Pattern

function hasProperty<T, K extends string>(
  obj: T,
  key: K
): obj is T & Record<K, unknown> {
  return typeof obj === 'object' && obj !== null && key in obj;
}

const data: unknown = { name: "Alice", age: 30 };

if (hasProperty(data, "name")) {
  // TypeScript knows data has a 'name' property
  console.log(data.name);
}

This generic guard checks if any object has a specific property, narrowing the type accordingly.

Key Takeaway: Generic type predicates let you write one reusable type guard function that narrows different types based on the same logical pattern, eliminating repetition while maintaining type safety.