Course contentsShow
← TypeScript
Lesson 910 of 1,79621. The unknown TypeFree lesson

Generic Constraints with unknown

See how unknown serves as a minimal constraint in generics when you truly accept any type but need safety.

Generic Constraints with unknown

You'll learn how to use unknown as the most permissive constraint when writing generics that truly accept any type while preserving type safety.

The Constraint Sweet Spot

When writing generic functions or types, you sometimes need to accept absolutely anything without restricting the type parameter. The instinct might be to use any as a constraint or leave it unconstrained, but there's a safer middle ground: constraining to unknown.

Why Constrain to unknown?

Think of unknown as a "soft boundary" for generics. It says: "I accept any type you give me, but I won't let you do unsafe operations inside this generic code." It's like a generic function saying, "Bring me anything, but I promise to handle it responsibly."

// ❌ Too permissive: T could be literally anything (even implicit any)
function wrapValue<T>(value: T) {
  return { data: value };
}

// ✅ Explicitly constrained to unknown: still accepts any type
function wrapValueSafe<T extends unknown>(value: T) {
  return { data: value };
}

Practical Use Case: Safe Pass-Through

The most common pattern is when you're creating wrappers or containers that don't need to inspect the value, just store and return it:

function createBox<T extends unknown>(content: T) {
  return {
    content,
    unwrap(): T {
      return content;
    }
  };
}

const numberBox = createBox(42);     // T = number
const stringBox = createBox("hi");   // T = string

The extends unknown constraint doesn't restrict what you can pass in—it accepts everything. But inside the function, TypeScript enforces that you can't perform unsafe operations on T without proper type guards.

The Safety Net

Unlike leaving the constraint off entirely (or using any), extends unknown prevents accidental assumptions:

function logAndReturn<T extends unknown>(value: T): T {
  // This would error if you tried unsafe operations:
  // console.log(value.toUpperCase()); // ❌ Error: Property doesn't exist
  
  console.log(value); // ✅ Safe: unknown allows inspection
  return value;
}

Key Takeaway: Use extends unknown as a generic constraint when you want to accept any type but maintain type safety inside the generic implementation—it's the principled way to say "truly anything goes."