Generics Basics
Generics Basics
Section titled βGenerics BasicsβWhat it means
Section titled βWhat it meansβA generic lets a function, class, or type work with multiple types while preserving the connection between them β instead of writing separate versions for number, string, etc. (or giving up and using any), you use a type parameter (conventionally T) that gets filled in with a concrete type at each call site.
Examples
Section titled βExamplesβfunction identity<T>(value: T): T { return value;}
identity<number>(42); // T is number, returns numberidentity("hello"); // T inferred as string, returns string
function firstItem<T>(items: T[]): T | undefined { return items[0];}firstItem([1, 2, 3]); // number | undefinedfirstItem(["a", "b"]); // string | undefined
class Box<T> { constructor(private value: T) {} getValue(): T { return this.value; }}const numberBox = new Box<number>(42);const stringBox = new Box("hello"); // T inferred as stringCommon mistake
Section titled βCommon mistakeβUsing any instead of a generic when a functionβs input and output types are actually related β any loses that connection entirely, so TypeScript can no longer verify the return value matches what was passed in.
function firstItem(items: any[]): any { return items[0];}const result = firstItem([1, 2, 3]);result.toUpperCase(); // no compile error, but crashes at runtime -- result is a number!
// With a generic, the relationship between input and output is preservedfunction firstItem<T>(items: T[]): T { return items[0];}const result = firstItem([1, 2, 3]); // TypeScript knows result: numberresult.toUpperCase(); // Error caught at compile time: Property 'toUpperCase' does not exist on type 'number'Quick practice
Section titled βQuick practiceβ-
What problem do generics solve that
anydoesnβt?Answer
Generics preserve the relationship between input and output types, so TypeScript can still catch type errors;anydiscards type information entirely, losing that safety. -
In
function identity<T>(value: T): T, what determines whatTbecomes at a given call site?Answer
Either an explicit type argument (identity<number>(42)) or, more commonly, TypeScript infers it automatically from the argument you pass. -
What does
class Box<T>let you do that a non-genericclass Boxcouldnβt?Answer
Create boxes that hold and return a specific, type-checked value type (Box<number>,Box<string>, etc.) using one shared implementation, instead of writing a separate class per type or losing type safety withany.