Skip to content
Live

Mastering TypeScript Generics

A deep dive into TypeScript generics — from basic type parameters to advanced conditional types and mapped types that make your code truly reusable.

By Soren Lindqvist9 min read

Why Generics Change Everything

TypeScript without generics is like a library with only one book. Generics let you write functions and classes that work with any type while still maintaining full type safety.

The Basic Pattern

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

const num = identity<number>(42);     // type: number
const str = identity<string>("hello"); // type: string

Generic Constraints

Use extends to constrain what types are allowed:

interface HasLength {
  length: number;
}

function logLength<T extends HasLength>(value: T): T {
  console.log(value.length);
  return value;
}

logLength("hello");   // ✓
logLength([1, 2, 3]); // ✓
logLength(42);        // ✗ Error: number has no length

Conditional Types

type IsArray<T> = T extends any[] ? true : false;

type A = IsArray<string[]>; // true
type B = IsArray<string>;   // false

Mapped Types

type Readonly<T> = {
  readonly [K in keyof T]: T[K];
};

type Optional<T> = {
  [K in keyof T]?: T[K];
};

Practical Patterns

  • Use keyof T to iterate over object keys safely
  • Use infer inside conditional types to extract nested types
  • Combine generics with utility types like Partial, Required, Pick, Omit

Generics are the foundation of every great TypeScript library. Master them and your code becomes infinitely more expressive.

Share

Written by

Soren Lindqvist

Engineer. Ships the TypeScript, Docker, and database pieces, usually after breaking them in production first.

programming

How to Contribute to Open Source

Your first open source contribution doesn't have to be a major feature. A practical guide to finding projects, making meaningful contributions, and building your reputation.

Amara Osei7 min read
react

State Management in 2024: What Actually Works

Redux is no longer the default answer. Compare Zustand, Jotai, TanStack Query, and React's built-in tools to find the right solution for your app.

Soren Lindqvist9 min read
css

Advanced Tailwind CSS Patterns

Go beyond utility classes. Learn Tailwind's plugin system, custom design tokens, component extraction, and the patterns that scale to large codebases.

Soren Lindqvist9 min read