Lesson 109 of 296
Generics
What you will learn
- The problem generics solve
- Generic functions and type inference
- Generic types and interfaces
- Generic classes
- A typed Result type
On this page
The problem
A function that returns the first item of an array:
function first(items: any[]): any {
return items[0];
}
const n = first([1, 2, 3]); n: any (we lost the type)With any, the result type is lost. Writing separate versions for numbers, strings and users would be silly.
Generic functions
A generic uses a type parameter: a placeholder for a type that is decided when the function is used. By convention it is often called T.
function first<T>(items: T[]): T | undefined {
return items[0];
}
const n = first([1, 2, 3]); n: number | undefined
const s = first(["a", "b"]); s: string | undefined
const u = first<User>(users); T given explicitlyTypeScript usually infers T from the arguments, so you rarely write it yourself.
Read <T> as "for some type T". The function works with any type while keeping the link between input and output types.
More examples
function wrapInArray<T>(value: T): T[] {
return [value];
}
function last<T>(items: readonly T[]): T | undefined {
return items.at(-1);
}
function pair<A, B>(a: A, b: B): [A, B] {
return [a, b];
}
const p = pair("age", 30); [string, number]Generic types
Types and interfaces can have type parameters too:
type ApiResponse<T> = {
data: T;
meta: { requestId: string };
};
type UserResponse = ApiResponse<User>;
type OrdersResponse = ApiResponse<Order[]>;Built-in generic types you already use: Array<T>, Promise<T>, Map<K, V>, Set<T>, Record<K, V>.
async function getUser(id: number): Promise<User> { ... }
const cache = new Map<string, User>();Generic classes
class Stack<T> {
#items: T[] = [];
push(item: T): void {
this.#items.push(item);
}
pop(): T | undefined {
return this.#items.pop();
}
peek(): T | undefined {
return this.#items.at(-1);
}
get size(): number {
return this.#items.length;
}
}
const numbers = new Stack<number>();
numbers.push(1);
numbers.push("two"); ErrorA typed Result type
A task from the study plan. Instead of throwing errors, a function can return success or failure as a discriminated union (Lesson 107):
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
function parseAge(input: string): Result<number, string> {
const age = Number(input);
if (!Number.isInteger(age) || age < 0) {
return { ok: false, error: "Age must be a whole number, 0 or more" };
}
return { ok: true, value: age };
}
const result = parseAge("42");
if (result.ok) {
console.log(result.value + 1); value: number
} else {
console.error(result.error); error: string
}Benefits: the caller cannot forget that the operation might fail, because the type forces a check. E = Error is a default type parameter (Lesson 110).
Helper functions make it shorter:
const ok = <T>(value: T): Result<T, never> => ({ ok: true, value });
const err = <E>(error: E): Result<never, E> => ({ ok: false, error });Naming type parameters
Tfor a single general type;KandVfor keys and values;Efor errors.- For complex code, use descriptive names:
TUser,TResponse.
Common mistakes
- Using
anyinstead of a generic. - Generics that are not needed: if
Tis only used once, a normal type is usually enough. - Writing the type argument when inference would work.
How to say it in an interview
"Generics are type parameters that let a function, type or class work with many types while preserving the relationship between them, for example first of T array returns T. TypeScript usually infers the type argument. I use generic types like ApiResponse of T, generic classes like a typed Stack, and a Result of T and E discriminated union for operations that can fail without throwing, which forces callers to handle both cases."
Key words
| Word | Meaning |
|---|---|
| Generic | Code that works with many types using type parameters |
| Type parameter | A placeholder type, such as T |
| Type argument | The actual type used for T, such as number |
| Result type | A union representing success or failure |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.