Sub topic 13
Deriving types with Partial, Pick, Omit, and Readonly
This chapter assumes you can declare interfaces and type aliases, you know optional and readonly properties, and you have seen generic type parameters such as Box<T>. You do not need to know mapped types in detail. The next chapter covers them, and this one only uses them as the mechanism behind the utility types.
Why derive types
Real programs have many types that are variations of one core shape. A Todo has a full form stored in a database. A form to create it has only some fields filled in. A list view shows only two fields. A frozen snapshot must not change.
You could write each variation by hand. That duplicates property names and types, and the copies drift apart when the original changes. A better approach is to derive the variations from the original. When Todo changes, every derived type changes with it.
TypeScript ships generic type aliases called utility types for the most common derivations. They are available globally and need no import. This chapter covers four: Partial, Pick, Omit, and Readonly.
The examples use this interface.
interface Todo {
title: string;
done: boolean;
note: string;
}Partial: make every property optional
Partial<T> produces a type with the same properties as T, each marked optional.
type TodoDraft = Partial<Todo>;
// { title?: string; done?: boolean; note?: string }
const draft: TodoDraft = { title: "Write chapter" };
const empty: TodoDraft = {};A typical use is an update function, where the caller supplies only the fields that change.
function updateTodo(todo: Todo, changes: Partial<Todo>): Todo {
return { ...todo, ...changes };
}
const original: Todo = { title: "Write", done: false, note: "" };
const updated = updateTodo(original, { done: true });
console.log(updated); // { title: "Write", done: true, note: "" }The function returns a full Todo, and the compiler accepts it because spreading changes over todo leaves every required property present.
A gotcha with explicit undefined
An optional property accepts undefined as a value. If you pass { note: undefined }, the spread above overwrites note with undefined, and the result no longer matches Todo at run time even though the compiler accepted it. This happens unless the compiler option exactOptionalPropertyTypes is enabled, which forbids assigning undefined to an optional property unless the type says so. If your update code receives data from outside, filter out undefined values before merging.
Partial is shallow
Partial affects only the top-level properties. Nested object types keep their required properties.
interface Profile {
name: string;
address: { city: string; zip: string };
}
const p: Partial<Profile> = {
address: { city: "Oslo" }, // error: Property 'zip' is missing
};If you need a recursive version, you have to write a custom mapped type. The built-in one does not do it.
Pick: keep only some properties
Pick<T, K> builds a type from T containing only the properties whose names are in the union K.
type TodoPreview = Pick<Todo, "title" | "done">;
// { title: string; done: boolean }
const preview: TodoPreview = { title: "Write", done: false };The second argument must be a union of keys that exist in T. A misspelled key is a compile error, which is a main benefit over hand-copying.
// type Bad = Pick<Todo, "titel">;
// error: Type '"titel"' does not satisfy the constraint 'keyof Todo'.Pick preserves modifiers. If a property was optional or readonly in T, it stays that way in the result.
Omit: remove some properties
Omit<T, K> is the opposite of Pick. It keeps everything except the listed keys.
type TodoWithoutNote = Omit<Todo, "note">;
// { title: string; done: boolean }Omit is useful when a type has many properties and you want to drop only one or two. A common pattern is describing the input to a "create" operation, where the system assigns the identifier.
interface User {
id: number;
name: string;
email: string;
}
type NewUser = Omit<User, "id">;
function createUser(input: NewUser): User {
return { id: Math.floor(Math.random() * 1_000_000), ...input };
}
console.log(createUser({ name: "Ada", email: "[email protected]" }));Omit does not check its keys
Unlike Pick, the key argument of Omit is typed as string | number | symbol. A misspelled key is silently accepted and removes nothing.
type Oops = Omit<Todo, "nnote">; // no error, and still has all three propertiesCheck the result when you write an Omit, or define a stricter version of your own for code where this matters.
type StrictOmit<T, K extends keyof T> = Omit<T, K>;
type Checked = StrictOmit<Todo, "note">; // ok
// type Wrong = StrictOmit<Todo, "nnote">; // error: does not satisfy keyof TodoOmit and unions
Omit does not distribute over unions. Applied to a union, it first reduces the union to its common properties, and the distinct members are lost.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
type Broken = Omit<Shape, "kind">; // {} : radius and side are gone, because they are not sharedTo remove a key from each member, use a distributive conditional type.
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown
? Omit<T, K>
: never;
type Fixed = DistributiveOmit<Shape, "kind">;
// { radius: number } | { side: number }Readonly: forbid assignment
Readonly<T> marks every property of T as readonly.
type FrozenTodo = Readonly<Todo>;
const frozen: FrozenTodo = { title: "Write", done: false, note: "" };
// frozen.done = true; // error: Cannot assign to 'done' because it is a read-only property.Like Partial, it is shallow. A readonly property that holds an object or array still allows mutation of the inner value.
interface Basket {
items: string[];
}
const basket: Readonly<Basket> = { items: ["apple"] };
basket.items.push("pear"); // allowed: only the items property is readonly
// basket.items = []; // errorFor arrays, use ReadonlyArray<string> or readonly string[] to block push.
Also remember that readonly exists only at compile time. It produces no run-time protection. If you need a real guarantee, combine it with Object.freeze.
Combining utility types
Utility types are ordinary generic aliases, so they nest. A common requirement is "a required id, with everything else optional".
type TodoPatch = Partial<Omit<Todo, "note">> & { note: string };A more practical example is a patch type that requires the identifier.
interface Article {
id: number;
title: string;
body: string;
published: boolean;
}
type ArticlePatch = Pick<Article, "id"> & Partial<Omit<Article, "id">>;
const patch: ArticlePatch = { id: 3, published: true };Read these from the inside out. Omit<Article, "id"> removes the identifier, Partial makes the rest optional, Pick<Article, "id"> keeps only the identifier, and & combines the two pieces.
The next diagram shows how each utility transforms the source type.
Interfaces and aliases in this chapter
Utility types always produce a type alias result, because they are aliases to mapped types. You cannot write interface X extends Partial<Todo> freely in every case: an interface can extend an object type whose members are statically known, and Partial<Todo> qualifies. It fails for a type that is a union, or for a generic utility applied to a type parameter whose members are unknown.
interface TodoUpdate extends Partial<Todo> {
reason: string;
}
const u: TodoUpdate = { reason: "typo fix", title: "Write chapters" };Use an alias when the result is a union or an intersection, and either construct when it is a plain object shape. The final chapter returns to this decision.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| A property you wanted to remove is still present | Misspelled key passed to `Omit` | Use `StrictOmit` or check the hover text |
| Union members lose their own properties after `Omit` | `Omit` does not distribute over unions | Use `DistributiveOmit` |
| Nested objects can still be changed | `Readonly` and `Partial` are shallow | Use a recursive mapped type or readonly nested types |
| Update produces `undefined` fields | Optional properties accept `undefined` | Filter values or enable `exactOptionalPropertyTypes` |
Exercise
Given interface Product { id: number; name: string; price: number; tags: string[] }, write a type ProductUpdate in which id is required and every other property is optional, and a type ProductSummary that has only name and price, both readonly.
Show answer
type ProductUpdate = Pick<Product, "id"> & Partial<Omit<Product, "id">>; type ProductSummary = Readonly<Pick<Product, "name" | "price">>;
Exercise
Why does Omit<Shape, "kind"> lose the radius and side properties when Shape is a union of two object types, and how do you fix it?
Show answer
Omit is not distributive. It applies keyof to the whole union, which keeps only the properties common to all members, and then rebuilds a single object type from those. Define DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never, which applies Omit to each union member separately.