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

Generics to Preserve Type Information

How generic functions prevent any by threading type parameters through transformations instead of erasing them.

Generics to Preserve Type Information

You'll learn: How generic functions prevent any by threading type parameters through transformations instead of erasing them.

The Type Information Loss Problem

When you work with transformations or wrappers without generics, TypeScript often falls back to any or forces you to use broad types that lose specificity. Imagine you have a function that wraps a value in an object:

function wrap(value: any) {
  return { value };
}

const result = wrap(42);
// result.value is 'any' — we lost the fact that it's a number

The type information about 42 being a number disappears into the any void.

How Generics Thread Type Information Through

Generics act like type variables that capture the input type and carry it through to the output. Think of them as a conveyor belt that keeps the original shape intact as it moves through your function:

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

const result = wrap(42);
// result.value is 'number' — type preserved!

const text = wrap("hello");
// text.value is 'string'

The type parameter T captures whatever type you pass in and ensures the wrapped value maintains that exact type.

Chaining Transformations Without Loss

This preservation becomes crucial when chaining operations:

function unwrap<T>(wrapped: { value: T }): T {
  return wrapped.value;
}

const num = unwrap(wrap(100));
// num is 'number', not 'any'

Each generic function in the chain preserves type information, preventing the dreaded any creep that forces you into type assertions later.

Key Takeaway: Generics preserve precise type information through transformations by capturing input types as type parameters and threading them to outputs, preventing the type erosion that any causes.