BeCuriouzBeCuriouz

Learn something new every day

🔷 TypeScript
🧬

Generic Functions: One Function, Any Type

💡 A type parameter <T> lets one function work over many types while preserving the exact input type in its output — safety without duplication.

Imagine an identity function that just returns whatever you give it. If you type it as (x: any) => any, it works — but you throw away all type information. Pass in a string and TypeScript no longer knows the result is a string. That's where generics come in: they let a function accept any type while preserving exactly which type flowed through it.

You introduce a type parameter — a placeholder written in angle brackets, conventionally — that stands for a type the caller decides:

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

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

The magic is type inference: you rarely write identity("hello"). TypeScript looks at the argument, sees a string, and binds T to string for that call. Because the return type is also T, the link between input and output is kept — unlike any, which would sever it. T is just a name; , , or work identically.

This is the core idea behind reusable, type-safe utilities. A function like first(arr: T[]): T | undefined works on an array of anything and still returns the precise element type — no casting, no lost autocomplete.

🧬 Generic Functions: One Function, Any Type — BeCuriouz