TS TypeScript

TypeScript: Generics

What you will learn

How generics let you write reusable functions and types that work with any type while preserving type safety.

The problem generics solve

Without generics, you'd need separate identityString, identityNumber, etc., or use any (losing type safety).

Basic generic function

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

let output1 = identity<string>('hello');  // type: string
let output2 = identity(42);              // type inferred: number

T is a type parameter -- a placeholder for the actual type. When you call the function, TS fills it in. The angle brackets <T> introduce the type parameter.

Generic interfaces

interface Result<T> {
    success: boolean;
    data: T;
    error?: string;
}

const userResult: Result<User> = {
    success: true,
    data: { id: 1, name: 'Alice' }
};

Generic constraints with extends

You can restrict what types are allowed:

interface HasLength {
    length: number;
}

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

logLength('hello');   // OK -- strings have length
logLength([1, 2]);    // OK -- arrays have length
// logLength(42);     // Error -- number has no .length

Common mistakes

  • Providing too many type parameters: <T, U, V> where two would do
  • Forgetting that arrow functions need <T,> (comma) in JSX files to avoid confusion with HTML tags

Quick check below!