Sub topic 13
Deriving Types with Partial, Pick, Omit, and Readonly
Prerequisites and the basic idea
This chapter assumes you know basic TypeScript annotations, JavaScript objects, and how to run the TypeScript compiler. It also assumes you understand interfaces and type aliases.
TypeScript provides utility types for creating a new type from an existing one. These utilities reduce repetition and keep related types synchronized. They affect compile-time checking only. They do not change the JavaScript object at runtime.
Consider a type for a task:
interface Todo {
id: number;
title: string;
done: boolean;
note: string;
}Making properties optional with `Partial`
Partial<T> creates a type in which every property of T is optional. It is useful for updates, where a caller may provide only the fields that should change.
type TodoUpdate = Partial<Todo>;
function updateTodo(id: number, changes: TodoUpdate): void {
console.log(id, changes);
}
updateTodo(1, { done: true });
updateTodo(1, { title: "Read the guide", note: "Chapter 2" });Partial<Todo> does not mean that properties become undefined at runtime. It means that code must handle the possibility that a property is missing.
A common error is to use Partial for a value that must be complete. A newly created Todo still needs every required property.
Selecting and excluding properties
Pick<T, K> creates a type containing only the properties listed by K. The keys must come from T.
type TodoPreview = Pick<Todo, "id" | "title" | "done">;
const preview: TodoPreview = {
id: 1,
title: "Read the guide",
done: false,
};Omit<T, K> does the opposite. It creates a type containing every property except those listed.
type NewTodo = Omit<Todo, "id">;
const newTodo: NewTodo = {
title: "Practice utility types",
done: false,
note: "",
};Use Pick when you want to state exactly which fields belong in a type. Use Omit when the type should follow the source type except for a small excluded set. Omit can silently include newly added fields later, so Pick may be safer for a public API boundary.
| Utility | Result |
|---|---|
| `Partial<T>` | All properties become optional |
| `Pick<T, K>` | Keeps only keys `K` |
| `Omit<T, K>` | Removes keys `K` |
| `Readonly<T>` | Prevents assignment to properties |
Preventing assignment with `Readonly`
Readonly<T> marks each top-level property as read-only.
type StoredTodo = Readonly<Todo>;
const stored: StoredTodo = {
id: 1,
title: "Review code",
done: false,
note: "",
};
// stored.done = true; // Error: cannot assign to a read-only propertyReadonly is shallow. If a property contains an object or array, the nested value is not automatically read-only. You need a separate deep-readonly type when nested mutation must also be prevented.
Exercise
Which utility type describes an update that may change only the title and note?
Show answer
Pick<Partial<Todo>, "title" | "note">.