TypeScript Generics - Complete Guide for Beginners to Advanced

Master TypeScript generics! Generic functions, interfaces, classes, constraints, and more!

Introduction

Generics let you write flexible, reusable code! Let's learn them!

What You Will Learn

  • Generic functions
  • Generic interfaces
  • Generic classes
  • Generic constraints

Prerequisites

Why Generics?

We want to write code that works with multiple types while preserving type safety!

Generic Functions!

function identity<T>(arg: T): T {
  return arg;
}
identity<string>("hello");
identity<number>(42);
identity("hello"); // Type inference!

Generic Interfaces!

interface Box<T> {
  value: T;
}

let numberBox: Box<number> = { value: 42 };
let stringBox: Box<string> = { value: "hello" };

Generic Constraints!

Limit what types can be used!

interface Lengthwise {
  length: number;
}

function logLength<T extends Lengthwise>(arg: T): number {
  return arg.length;
}

logLength("hello"); // 5
logLength([1, 2, 3]); // 3

Best Practices

  1. Use descriptive type parameters: T, U, TValue, etc!
  2. Use constraints when needed: Narrow down possibilities!
  3. Use type inference: Let TS handle it!

Summary

Generics make your code reusable and type-safe!

Related Articles

Previous Tutorial

Union & Intersection Types

Next Tutorial

Let's learn utility types! → Utility Types