Lesson 3 of 4 · 10 min · TypeScript fundamentals
Generics and utility types
What you will learn
- Write generic functions, interfaces and classes
- Constrain generics with
extendsand usekeyof - Use the built-in utility types:
Partial,Required,Readonly,Pick,Omit,Record,Exclude,Extract,NonNullable,ReturnType,Parameters,Awaited - Build new types from existing ones
- Type a reusable API helper
In simple words
A generic is a blank in a type that gets filled in later. A function first(list) should work for a list of numbers, of names or of orders, and return the same kind of thing that was in the list. Without generics you would write it three times or lose type safety with any. Utility types are ready-made tools for reshaping an existing type: make every property optional, pick only some, leave some out.
Words to know
- Generic: a type or function with a type parameter, such as
Array<T>. - Type parameter: the placeholder, usually
T, filled in when you use the generic. - Constraint: a limit on what a type parameter may be, written with
extends. - Utility type: a built-in generic type that transforms another type.
Generic functions
function first<T>(items: T[]): T | undefined {
return items[0];
}
const a = first([1, 2, 3]); // T inferred as number: a is number | undefined
const b = first(["sql", "excel"]); // string | undefined
const c = first<Order>([]); // explicit type argument (rarely needed)
function pair<A, B>(a: A, b: B): [A, B] {
return [a, b];
}
T is a normal type name by convention (T, U, K, V, E, or descriptive names such as TItem). TypeScript infers T from the arguments, so you rarely write it.
Generic types and interfaces
interface ApiResponse<T> {
data: T;
status: number;
fetchedAt: Date;
}
type Paged<T> = { items: T[]; page: number; total: number };
const orders: ApiResponse<Order[]> = await getOrders();
const page: Paged<Customer> = { items: [], page: 1, total: 0 };
class Stack<T> {
private items: T[] = [];
push(item: T): void { this.items.push(item); }
pop(): T | undefined { return this.items.pop(); }
}
const s = new Stack<number>();
s.push(1);
s.push("two"); // Error: string is not assignable to number
Built-in generics you already use: Array<T>, Promise<T>, Map<K, V>, Set<T>, Record<K, V>, Partial<T>.
Constraints
Sometimes T must have certain properties. Constrain it with extends:
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
longest("abc", "de"); // works for strings
longest([1, 2], [3]); // and arrays
longest(10, 20); // Error: number has no length
function byId<T extends { id: number }>(items: T[], id: number): T | undefined {
return items.find((item) => item.id === id);
}
keyof and indexed access
keyof T is the union of the property names of T; T[K] is the type of that property:
interface Customer { id: number; name: string; email: string }
type CustomerKey = keyof Customer; // "id" | "name" | "email"
type NameType = Customer["name"]; // string
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const customer: Customer = { id: 1, name: "Asha", email: "a@example.com" };
getProp(customer, "name"); // string
getProp(customer, "phone"); // Error: not a key of Customer
Two type parameters tied together with K extends keyof T give type-safe property access, a very common pattern.
Default type parameters
interface Result<T = string, E = Error> { value?: T; error?: E }
const r: Result = { value: "ok" }; // T = string, E = Error by default
Utility types
TypeScript includes generic helpers that transform types. Start from:
interface User { id: number; name: string; email: string; role: "admin" | "user" }
| Utility | Result | Example |
|---|---|---|
Partial<T> |
all properties optional | Partial<User> for update payloads |
Required<T> |
all properties required | |
Readonly<T> |
all properties readonly | Readonly<User> |
Pick<T, K> |
only the listed keys | Pick<User, "id" | "name"> |
Omit<T, K> |
everything except the listed keys | Omit<User, "id"> for a create request |
Record<K, V> |
an object with keys K and values V | Record<User["role"], number> |
Exclude<U, X> |
remove members from a union | Exclude<"a" | "b", "a"> is "b" |
Extract<U, X> |
keep matching members of a union | |
NonNullable<T> |
removes null and undefined |
|
ReturnType<F> |
the return type of a function | ReturnType<typeof getOrder> |
Parameters<F> |
the parameter types as a tuple | |
Awaited<T> |
unwraps a Promise type |
Awaited<ReturnType<typeof fetchUser>> |
type CreateUser = Omit<User, "id">; // { name; email; role }
type UpdateUser = Partial<Omit<User, "id">>; // any subset of the editable fields
type UserSummary = Pick<User, "id" | "name">;
const rolesCount: Record<User["role"], number> = { admin: 2, user: 40 };
function updateUser(id: number, changes: UpdateUser): Promise<User> { /* ... */ }
updateUser(1, { email: "new@example.com" }); // OK
updateUser(1, { id: 5 }); // Error: id is not editable
type Order = Awaited<ReturnType<typeof getOrder>>; // derive the type from the function: one source of truth
Deriving types from other types (and from values with typeof) keeps them in sync: change the source, and everything updates, so you do not have duplicated definitions that drift apart.
Mapped and conditional types (a taste)
Utility types are built from two features you will meet in libraries:
// Mapped type: transform each property
type Optional<T> = { [P in keyof T]?: T[P] }; // this is Partial<T>
type Getters<T> = { [P in keyof T as `get${Capitalize<string & P>}`]: () => T[P] };
// Conditional type: choose a type based on a condition
type ElementOf<T> = T extends (infer U)[] ? U : T;
type X = ElementOf<string[]>; // string
You will rarely write these in application code, but reading them in library types helps.
Typing an API helper
class HttpError extends Error {
constructor(public readonly status: number, message: string) { super(message); }
}
async function api<T>(path: string, init?: RequestInit): Promise<T> {
const response = await fetch(`/api${path}`, init);
if (!response.ok) throw new HttpError(response.status, `Request failed: ${path}`);
return (await response.json()) as T; // a trusted assertion: the server must match
}
const order = await api<Order>("/orders/5"); // order: Order
const orders = await api<Order[]>("/orders");
Honest note: the as T is an assertion; TypeScript cannot know what the server sends. For data that matters, validate with a schema (Zod) and infer T from it, so the type is checked at run time too.
Guidelines
- Use generics when a type relationship must be preserved (input type equals output type, an object and its key). If a function does not relate types, a plain type is simpler.
- Do not use generics for the sake of it: a type parameter used only once is usually a sign you do not need it.
- Name parameters meaningfully when there are several (
TInput,TOutput). - Prefer utility types and derived types to retyping shapes by hand.
- Constrain parameters so that you can use their properties safely.
- Avoid
anyinside generic code; useunknownand constraints. - Complex type-level programming (nested conditional types) is hard to read and slows the compiler; keep application types simple.
Common mistakes
- Generic functions that return
anyor cast their result without need. - Forgetting constraints, then using properties that may not exist.
- Retyping the same shape in several places instead of deriving it.
- Assuming
Partial<T>makes nested properties optional (it is shallow). - Type parameters used once that add noise.
- Over-clever mapped and conditional types in everyday code.
Try it yourself
- Write
first<T>,last<T>andgroupBy<T, K extends string>(items: T[], key: (item: T) => K): Record<K, T[]>. - Write
getProp<T, K extends keyof T>(obj, key)and show that a misspelt key fails to compile. - From a
Userinterface, deriveCreateUser,UpdateUserandUserSummarywith utility types. - Derive the type of an API function's resolved value with
Awaited<ReturnType<...>>. - Type a generic
api<T>()helper and then replace its assertion with a Zod schema.
Check yourself
What problem do generics solve?
They let one function or type work with many types while preserving the relationship between them (for example, a list of T returns a T), without resorting to any.
What does T extends { length: number } mean?
The type parameter T must have a numeric length property, so the function body may use length safely.
What is the difference between Pick and Omit?
Pick<T, K> keeps only the listed keys; Omit<T, K> keeps everything except the listed keys.
What does Partial<T> do?
It makes every property of T optional (only at the top level).
Interview questions
What are generics in TypeScript? Give an example.
Type parameters that let code work over different types while staying type-safe, such as function first<T>(items: T[]): T | undefined returning the element type of whatever array is passed.
Explain keyof and indexed access types.
keyof T gives the union of property names of T; T[K] gives the type of property K. Together, K extends keyof T lets you write type-safe getProp(obj, key) returning T[K].
How would you type the payload of an update endpoint where all fields are optional except the id?
With utility types, for example Partial<Omit<User, "id">> for the changes and a separate id: number parameter.
Summary
- Generics keep types connected:
function first<T>(items: T[]): T | undefined; constrain withextendsand usekeyof. - Utility types (
Partial,Pick,Omit,Record,ReturnType,Awaitedand others) reshape types without repeating them. - Derive types from other types and values to keep a single source of truth.
- Use generics only where they add value, and validate untrusted data at run time.
Going deeper
- TypeScript Handbook: Generics: functions, classes, constraints.
- TypeScript Handbook: Utility types: every built-in utility type.
- TypeScript Handbook: Keyof type operator:
keyofin detail. - TypeScript Handbook: Mapped types: the building block of utility types.
See how much of this you can explain
A free mock interview asks you new questions on TypeScript for JavaScript developers for Frontend Developer and scores every answer, with what to fix.