Built-in utility types: Partial, Pick, Omit, Record and more
Course contents (16 lessons)
- Getting started
- Why TypeScript? What it is and what it is not
- Setting up TypeScript: tsc and tsconfig.json
- Core types
- Basic types: primitives, arrays, tuples, any and unknown
- Typing functions: parameters, returns, optionals and overloads
- Objects, interfaces and type aliases
- Unions, literals and enums
- Union types and type narrowing
- Literal types, enums and as const
- Classes and generics
- Classes in TypeScript
- Generics: writing reusable typed code
- Built-in utility types: Partial, Pick, Omit, Record and more
- Advanced types
- Mapped and conditional types
- Modules, type imports and declaration files
- TypeScript in real projects
- Typing async code and API responses
- Strict mode and compiler flags that matter
- Migrating a JavaScript project to TypeScript
- Final project: a type-safe task manager
Reusing types without copying them
Imagine a User interface with ten fields. Now you need a type for the "update user" form, where every field is optional. And another type for a public profile without the password hash. Writing each of them out by hand duplicates information, and the copies drift apart.
TypeScript ships with utility types that create new types from existing ones. They are generic types, and they are available everywhere with no import.
We will use this interface through the lesson:
interface User {
id: number;
name: string;
email: string;
passwordHash: string;
role: "admin" | "member";
}
Partial and Required
Partial<T> makes every property optional. Required<T> does the opposite.
interface User {
id: number;
name: string;
email: string;
passwordHash: string;
role: "admin" | "member";
}
function updateUser(user: User, changes: Partial<User>): User {
return { ...user, ...changes };
}
const sara: User = { id: 1, name: "Sara", email: "s@example.com", passwordHash: "x", role: "member" };
const updated = updateUser(sara, { name: "Sara Khan" });
console.log(updated.name, updated.role); // Sara Khan member
Partial is the classic choice for update functions and for options objects where everything has a default.
Pick and Omit
Pick<T, Keys> builds a type with only the chosen properties. Omit<T, Keys> builds one with everything except the chosen ones.
interface User {
id: number;
name: string;
email: string;
passwordHash: string;
role: "admin" | "member";
}
type PublicUser = Omit<User, "passwordHash">;
type UserSummary = Pick<User, "id" | "name">;
type NewUser = Omit<User, "id">;
const summary: UserSummary = { id: 1, name: "Ali" };
function toPublic(user: User): PublicUser {
const { passwordHash, ...rest } = user;
return rest;
}
console.log(summary.name, toPublic({ id: 2, name: "Z", email: "z@example.com", passwordHash: "h", role: "admin" }));
The keys you pass must exist on the type. If you rename a property in User, every Pick and Omit that mentions the old name shows an error. That is much better than a copy that quietly stops matching.
Readonly
interface Settings {
theme: string;
fontSize: number;
}
const defaults: Readonly<Settings> = { theme: "light", fontSize: 14 };
// defaults.theme = "dark"; // Error: read-only
console.log(defaults.theme);
const list: readonly number[] = [1, 2, 3];
// list.push(4); // Error
console.log(list.length);
Readonly<T> is shallow. Nested objects can still be changed. It only protects at compile time.
Record
Record<Keys, Value> builds an object type with the given keys, all of the same value type. It is the neat way to write a dictionary or a lookup table.
type Role = "admin" | "editor" | "viewer";
const permissions: Record<Role, string[]> = {
admin: ["read", "write", "delete"],
editor: ["read", "write"],
viewer: ["read"],
};
console.log(permissions.editor.join(", "));
// If you forget a role, the compiler reports that it is missing.
const wordCount: Record<string, number> = {};
for (const word of ["a", "b", "a"]) {
wordCount[word] = (wordCount[word] ?? 0) + 1;
}
console.log(wordCount);
When the keys are a union, Record forces you to provide every one. That is useful for things like a label for each status: adding a new status later makes the compiler show every place that must be updated.
Extract, Exclude and NonNullable
These work on unions:
type Event = "click" | "hover" | "keydown" | "keyup";
type KeyEvent = Extract<Event, "keydown" | "keyup">; // "keydown" | "keyup"
type MouseEvent2 = Exclude<Event, KeyEvent>; // "click" | "hover"
type MaybeName = string | null | undefined;
type Name = NonNullable<MaybeName>; // string
const e: KeyEvent = "keyup";
const m: MouseEvent2 = "click";
const n: Name = "Ali";
console.log(e, m, n);
ReturnType, Parameters and Awaited
These read information from function types:
function createUser(name: string, age: number) {
return { id: Date.now(), name, age, createdAt: new Date() };
}
type NewUser = ReturnType<typeof createUser>;
type CreateArgs = Parameters<typeof createUser>; // [name: string, age: number]
const args: CreateArgs = ["Sara", 28];
const user: NewUser = createUser(...args);
console.log(user.name);
async function loadCount(): Promise<number> {
return 5;
}
type Count = Awaited<ReturnType<typeof loadCount>>; // number
const count: Count = 10;
console.log(count);
typeof createUser takes the type of an existing function value. ReturnType then extracts what it returns, so you do not need to write an interface by hand, and the type always follows the code. Awaited unwraps a promise type, which is what you need for the result of an async function.
Combining them
Utility types compose:
interface Article {
id: number;
title: string;
body: string;
published: boolean;
}
// For editing: id is required and cannot change, everything else is optional
type ArticleUpdate = Pick<Article, "id"> & Partial<Omit<Article, "id">>;
const change: ArticleUpdate = { id: 3, title: "New title" };
console.log(change.id, change.title);
Read these from the inside out: Omit removes id, Partial makes the rest optional, Pick keeps only id, and & joins the two.
Quick reference
| Utility | Result |
|---|---|
Partial<T> | All properties optional |
Required<T> | All properties required |
Readonly<T> | All properties read-only |
Pick<T, K> | Only the keys K |
Omit<T, K> | Everything but the keys K |
Record<K, V> | Object with keys K and values V |
Extract<U, M> / Exclude<U, M> | Keep or remove members of a union |
NonNullable<T> | Remove null and undefined |
ReturnType<F> / Parameters<F> | Function return and parameter types |
Awaited<P> | The value a promise resolves to |
Common mistakes
- Rewriting a type by hand when a utility would do. The copy will drift.
- **Expecting
Readonlyto be deep.** Nested objects stay mutable. - **Using
Partialfor data that is not actually optional.** A function that takesPartial<User>also accepts{}. - **Using
Omitwith a misspelt key.**Omitdoes not check that the key exists, unlikePick. A typo silently omits nothing. - **Reaching for
Record<string, any>.** Give the value a real type.
Try it yourself
- From an interface
Productwith five fields, buildProductPreviewusingPick, andNewProductusingOmit. - Create a
Record<"draft" | "published" | "archived", string>with a label for each state. - Use
ReturnTypeto get the type ofDate.nowand ofJSON.parse. What do you get? - Write a function
merge<T>(base: T, changes: Partial<T>): T.
interface User {
id: number;
name: string;
email: string;
passwordHash: string;
role: "admin" | "member";
}
function updateUser(user: User, changes: Partial<User>): User {
return { ...user, ...changes };
}
const sara: User = { id: 1, name: "Sara", email: "s@example.com", passwordHash: "x", role: "member" };
const updated = updateUser(sara, { name: "Sara Khan" });
console.log(updated.name, updated.role); // Sara Khan member
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account