Lesson 18 / 26

Generic Functions

Write one function that works with many types, safely.

A generic identity function

<T> is a type placeholder, filled in by whatever type is actually passed — unlike any, the relationship between input and output stays type-safe.

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

const a = identity<number>(42);      // a: number
const b = identity("hello");         // b: string, T inferred

A labeled box

Think of T as a labeled shipping box — you don't know what's inside until it's packed, but whatever goes in comes out the same, unchanged.

A generic array helper

The same generic function works with arrays of numbers, strings, or objects — TS keeps every call type-checked.

function firstElement<T>(arr: T[]): T | undefined {
  return arr[0];
}

firstElement([1, 2, 3]);          // number | undefined
firstElement(["a", "b"]);         // string | undefined