Course contentsShow
← TypeScript
Lesson 622 of 1,79615. Generic ConstraintsFree lesson

Constraining to Primitive Types

Use extends to restrict type parameters to specific primitive types like string or number.

Constraining to Primitive Types

What you'll learn: How to use extends with generics to restrict type parameters to specific primitive types like string, number, or boolean.

Why Constrain to Primitives?

Sometimes you want a generic function that works with any string or any number, but not with objects, arrays, or other complex types. Without constraints, TypeScript allows any type to be passed. By adding extends, you tell TypeScript: "This type parameter must be a primitive type (or a subtype of it)."

Think of it like a filter on a hiring form: instead of accepting "any applicant," you specify "must have a computer science degree" — similarly, T extends string means "must be a string type."

Basic Syntax

function repeat<T extends string>(value: T, times: number): T[] {
  return Array(times).fill(value);
}

const result = repeat("hello", 3); // ✅ Works
// const bad = repeat(123, 3); // ❌ Error: number isn't assignable to string

Here, T extends string means T must be string or a string literal type. You cannot pass numbers, objects, or anything else.

Constraining to Other Primitives

function double<T extends number>(value: T): number {
  return value * 2;
}

function negate<T extends boolean>(value: T): boolean {
  return !value;
}

Each constraint ensures the function only accepts the specified primitive family.

Key Takeaway: Use extends with primitive types like string, number, or boolean to restrict generic type parameters and enforce type safety at compile time.