Latticework

Command Palette

Search for a command to run...

TypeScript

Generics

16 min

Explanation

A generic function is written once but works correctly across many types, without losing type information the way any would. <T> declares a type PARAMETER — a placeholder TypeScript fills in based on how the function is actually called. firstOf([1,2,3]) infers T = number and returns number | undefined; firstOf(["a"]) infers T = string and returns string | undefined — same function body, different return type each time, checked correctly either way. This is different from any, which would compile but silently throw away all type information, letting mistakes slip through uncaught.

function firstOf<T>(items: T[]): T | undefined {
  return items[0];
}
console.log(firstOf([1, 2, 3]));
// 1  (TypeScript infers T = number here)
Try it

Same wrapInArray function, called with a number then a string -- T is inferred fresh at each call site, so the return type tracks whatever was actually passed in.

Loading editor…
Exercise

Write a generic function `firstOf<T>(items: T[]): T | undefined` that returns the first element of `items`, or `undefined` if the array is empty.

Quiz

Why write firstOf<T>(items: T[]): T | undefined instead of firstOf(items: any[]): any?

Checkpoint

You can write generic functions that preserve type information across different call sites, instead of falling back to any.