Technology

TypeScript Generics, Explained Without the Jargon

Intermediate 18 min read VisTechie Team Technology
1 views

The problem generics are solving

Say you want a function that wraps any value in an array. Without generics you'd either duplicate the function per type, or fall back to any - and any quietly throws away every bit of type information you had.

// Without generics - loses type information
function wrapInArray(value: any): any[] {
  return [value];
}

const result = wrapInArray(42); // TypeScript thinks this is any[]

Your first generic function

Add a type parameter - usually called T by convention - in angle brackets. TypeScript figures out what T should be based on whatever you actually pass in.

function wrapInArray<T>(value: T): T[] {
  return [value];
}

const nums = wrapInArray(42);    // T is inferred as number → number[]
const strs = wrapInArray("hi");  // T is inferred as string → string[]

Generics in interfaces

They're not just for functions - interfaces use them constantly to describe reusable shapes of data.

interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
}

const res: ApiResponse<{ id: string; name: string }> = {
  success: true,
  data: { id: "abc", name: "Alice" },
};

Constraining what T can be

Use extends when you need to guarantee a certain property exists, so you can safely use it inside the function.

function getLength<T extends { length: number }>(value: T): number {
  return value.length;
}

getLength("hello");   // 5
getLength([1, 2, 3]); // 3
getLength(42);        // Error: number has no .length
1 views

Comments

0/2000

Comments are reviewed before being published.

Loading comments...

Related Articles