Course contentsShow
← TypeScript
Lesson 1663 of 1,79638. Common Patterns and AntipatternsFree lesson

When Generics Are Better: Type Preservation Needed

Use generics when the exact type must flow through a function and be preserved in the return type.

When Generics Are Better: Type Preservation Needed

What you'll learn: You'll understand when to choose generics over unions by recognizing situations where the exact input type must flow through and be preserved in the output.

The Core Principle

Generics shine when you need type preservation — when the specific type that goes into a function must be reflected in what comes out. Without generics, TypeScript would widen or lose the precise type information, forcing you to work with a broader, less useful type.

The Problem Unions Can't Solve

Imagine a function that wraps a value in an object:

type Result = 
  | { value: string }
  | { value: number }
  | { value: boolean };

function wrapWithUnion(input: string | number | boolean): Result {
  return { value: input };
}

const wrapped = wrapWithUnion("hello");
// Type: Result (all three possibilities)
// TypeScript doesn't know it's specifically { value: string }

You've lost precision! TypeScript only knows wrapped is one of three shapes, not which specific one.

Generics Preserve the Connection

function wrap<T>(input: T): { value: T } {
  return { value: input };
}

const wrapped = wrap("hello");
// Type: { value: string } — exact type preserved!

const numberWrapped = wrap(42);
// Type: { value: number }

The generic T acts like a type-level variable that "remembers" what you passed in and ensures the output reflects that exact type.

When Type Preservation Matters

You need generics when:

  • Array methods must return arrays of the same element type
  • Promise wrappers must preserve the resolved value type
  • Data transformation where output type depends on input type
  • Builders that need method chaining with type accumulation

Real-World Pattern

function firstElement<T>(arr: T[]): T | undefined {
  return arr[0];
}

const names = ["Alice", "Bob"];
const first = firstElement(names);
// Type: string | undefined (not string | number | boolean | undefined)

Without the generic, you'd get back a useless any or overly broad union that doesn't reflect the specific array type you passed.

Key Takeaway: Use generics when the exact type must flow through your function and be preserved in the return type — unions combine possibilities, but generics maintain the specific relationship between input and output types.