Lesson 41 of 50TypeScript
Utility Types
Derive new types from existing ones with Partial, Pick, Omit, Record, ReturnType and friends, compose your own, and avoid the Omit traps.
In a real app, one entity spawns many related shapes: the User in the database, the body of POST /users (no id yet), the body of PATCH /users/:id (every field optional), the public profile (no password hash). Copying those shapes by hand means they drift apart. Utility types are built-in generics that derive one type from another, so a change to User flows everywhere automatically.
The base type
Every example in this lesson starts from this one type:
interface User {
id: number;
email: string;
name: string;
passwordHash: string;
bio?: string;
}Define the entity once. Everything else is derived from it.
Changing modifiers: Partial, Required, Readonly
Partial<T> makes every property optional. It is the classic type for an update payload, where the client sends only what changed.
function updateUser(id: number, changes: Partial<User>) { /* ... */ }
updateUser(7, { name: "Ada L." }); // OK
updateUser(7, { nmae: "Ada L." });
// Error: Object literal may only specify known properties, but 'nmae' does not exist in type 'Partial<User>'. Did you mean to write 'name'?Required<T> does the opposite: every ? is removed. Useful for "config after defaults are applied".
Readonly<T> marks every property readonly. Good for state you must not mutate, like a Redux store or React props.
Press Run (⌘ Enter) to see what happens.Choosing keys: Pick, Omit, Record
Pick<T, Keys> keeps only the listed keys. Omit<T, Keys> keeps everything except them. Keys are written as a union of string literals.
type UserPreview = Pick<User, "id" | "name">;
// { id: number; name: string }
type PublicUser = Omit<User, "passwordHash">;
// { id: number; email: string; name: string; bio?: string }
type NewUser = Omit<User, "id">;
// The POST body: the database assigns the idPublicUser is the important one in practice: the return type of your API handler. If someone tries to send the hash to the browser, it is a compile error rather than a security incident.
Record<Keys, Value> builds an object type from a set of keys and a value type, as you saw with lookup tables.
Press Run (⌘ Enter) to see what happens.Delete the archived line from LABELS in a real editor and the whole object turns red: Record demands every key.
createdAt field to User. Which type picks it up automatically?Filtering unions: Exclude, Extract, NonNullable
These work on unions rather than object keys.
type Status = "draft" | "published" | "archived";
type Visible = Exclude<Status, "archived">; // "draft" | "published"
type Done = Extract<Status, "published" | "archived">; // "published" | "archived"
type MaybeName = string | null | undefined;
type Name = NonNullable<MaybeName>; // stringExclude removes members that match, Extract keeps only members that match, and NonNullable removes null and undefined. In fact, Omit<T, K> is built from Pick and Exclude under the hood: pick every key of T except those in K.
Types from functions: ReturnType, Parameters, Awaited
Sometimes the source of truth is a function, not a type. These utilities read types off a function, so you never write them twice. Note the typeof: utility types take types, and typeof fn turns a function value into its type.
function createSession(userId: number, ttlSeconds = 3600) {
return { userId, token: crypto.randomUUID(), expiresAt: Date.now() + ttlSeconds * 1000 };
}
type Session = ReturnType<typeof createSession>;
// { userId: number; token: string; expiresAt: number }
type SessionArgs = Parameters<typeof createSession>;
// [userId: number, ttlSeconds?: number]
async function fetchUser(id: number): Promise<User> { /* ... */ }
type Fetched = Awaited<ReturnType<typeof fetchUser>>;
// User (Awaited unwraps the Promise)ReturnType is especially handy for third-party functions that do not export their result type.
What does this print?
type User = { id: number; name: string; passwordHash: string };
type PublicUser = Omit<User, "passwordHash">;
const user: User = { id: 1, name: "Ada", passwordHash: "x9f" };
const shown: PublicUser = user;
console.log(Object.keys(shown).length);Types from classes: InstanceType and ConstructorParameters
A class name means two different things in TypeScript. In a type position, EmailService is the type of an instance. typeof EmailService is the type of the class itself: the constructor function you call with new, with its static members. Mixing them up gives errors like "Type 'typeof EmailService' is missing the following properties from type 'EmailService'", which just means you passed the class where an instance was expected.
When code receives a class as a value (factories, dependency injection containers, test helpers, plugin registries), two utilities read types off the constructor, the same way ReturnType and Parameters read them off a function:
ConstructorParameters<C>: the tuple of argumentsnew C(...)takes.InstanceType<C>: whatnew C(...)produces.
Press Run (⌘ Enter) to see what happens.The any in Ctor is deliberate, and it is how the built-in definitions are written too. With unknown[] instead, a constructor that needs a string would not fit, because a function that demands a string cannot stand in for one that accepts anything. The any lives only in the constraint. Callers still get exact types out. If your factory must also accept abstract classes, write the constraint as abstract new (...args: any) => any.
Awaited has a little more to it than unwrapping one promise. It is recursive (Awaited<Promise<Promise<number>>> is number), it leaves non-promises alone, and it distributes over unions, so Awaited<Promise<string> | number> is string | number. That matches what await does at runtime, which is why the types of Promise.all and Promise.allSettled are written with it.
class Repo { constructor(readonly url: string) {} }, which type describes the value you pass to create(Repo, "/api")?Composing your own: PartialBy and Simplify
The built-ins change every key. Real payloads usually need something finer: "a User, but id and createdAt are optional because the database fills them in". You build that by composing the built-ins:
type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
type RequiredBy<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
interface User { id: number; email: string; name: string; passwordHash: string; createdAt: Date }
type UserInput = PartialBy<User, "id" | "createdAt">;
// email, name, passwordHash required; id and createdAt optional
type Draft = { title?: string; body?: string; publishedAt?: Date };
type Publishable = RequiredBy<Draft, "title" | "body">;
// title and body required, publishedAt still optionalRead PartialBy as a sentence: take everything except K unchanged, then add back K with each key optional. Note the constraint K extends keyof T. It means PartialBy<User, "nmae"> is an error, which matters more than it looks (see the next section).
One cosmetic problem: hover over UserInput and the editor shows Omit<User, "id" | "createdAt"> & Partial<Pick<User, "id" | "createdAt">>, not the fields. A tiny helper fixes that:
type Simplify<T> = { [K in keyof T]: T[K] } & {};
type UserInput = Simplify<PartialBy<User, "id" | "createdAt">>;
// hover: { email: string; name: string; passwordHash: string; id?: number; createdAt?: Date }The mapped type walks the intersection and rebuilds it as one flat object. The & {} nudges the compiler into showing the expanded form instead of the alias name. The type is identical either way. This only changes what you read in tooltips and error messages, which is often exactly what a reviewer needs.
Omit pitfalls: unions and typos
Omit has two behaviours that surprise people in real code.
It does not check its keys. The built-in is declared as Omit<T, K extends keyof any>, so K can be any string. Omit<User, "pasword"> compiles, removes nothing, and your "safe" public type still contains password. When the keys come from a refactor, that is a silent leak. A strict version is one line:
type StrictOmit<T, K extends keyof T> = Omit<T, K>;
type Safe = StrictOmit<User, "pasword">;
// Error: Type '"pasword"' does not satisfy the constraint 'keyof User'.The looseness is deliberate (sometimes you want to omit a key that only some types have), but for your own entity types the strict form is almost always what you want.
It flattens unions. Take a discriminated union of payment methods and try to make a "new payment method" type without the id:
type Card = { id: string; kind: "card"; last4: string };
type Bank = { id: string; kind: "bank"; iban: string };
type Method = Card | Bank;
type NewMethod = Omit<Method, "id">;
const m: NewMethod = { kind: "card", last4: "4242" };
// Error: Object literal may only specify known properties, and 'last4' does not exist in type 'NewMethod'.Omit is built on keyof T, and keyof (Card | Bank) is only the keys both members share: "id" | "kind". So NewMethod is { kind: "card" | "bank" }, and the union is gone. The fix is to apply Omit to each member separately. A conditional type over a naked type parameter distributes over a union, so this does exactly that:
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
type NewMethod = DistributiveOmit<Method, "id">;
// Omit<Card, "id"> | Omit<Bank, "id">
const ok: NewMethod = { kind: "card", last4: "4242" };T extends unknown is always true. It is there only to trigger distribution. You will see why conditional types behave this way in Advanced types. The same trap applies to Pick and to keyof on any union, so whenever a derived type of a union "loses" fields, distribution is the first thing to check.
type A = { id: string; a: number } and type B = { id: string; b: boolean }, what is keyof (A | B)?Write your own or use type-fest?
type-fest is a popular package of utility types, written and tested by people who have hit every edge case. It ships only types, so it adds nothing to your bundle. It has versions of everything in this lesson: SetOptional and SetRequired (like PartialBy and RequiredBy), Except (a strict Omit), Simplify, DistributedOmit, plus deep types such as PartialDeep, ReadonlyDeep and JsonValue.
A sensible rule for a team:
- Write the one-liners yourself.
StrictOmit,PartialBy,Simplifyare short enough to read in review. Put them in onetypes/utils.tsfile so nobody writes them twice. - Import the recursive ones. A correct
PartialDeephas to decide what to do with arrays, tuples,Map,Set,Dateand functions. The hand-writtenDeepPartialyou will build in Advanced types is a good exercise and a poor production dependency. - Mind your public types. If a library you publish exposes a type-fest type in its
.d.tsfiles, type-fest must be a real dependency, not a dev dependency, or your users get unresolved types. - Prefer a schema when data crosses a boundary. If the shape comes from an API, derive the type from a Zod schema with
z.inferinstead of hand-building it with utilities. Then the type and the runtime check cannot drift apart.
Type-level code costs compile time and readability. If a utility needs a paragraph of comments to explain, the domain model probably wants a plain, named type instead.
Picking the right utility
Match each real need to the utility type.
address.city optional in Partial<Profile>?type Profile = { name: string; address: { city: string; zip: string } };
type Patch = Partial<Profile>;Build a PATCH body
A settings form loads a record, the user edits it, and you send only what changed to PATCH /api/users/:id. Write:
function changedFields<T extends object>(before: T, after: T): Partial<T>Return an object with every key of after whose value is not === to the same key in before. Compare shallowly (nested objects are compared by reference).
changedFields({ name: "Ada", email: "a@x.io", age: 36 }, { name: "Ada", email: "ada@x.io", age: 37 })
→ { email: "ada@x.io", age: 37 }Typed omit
Write the runtime twin of the Omit utility type: return a copy of obj without the listed keys.
function omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>omit({ id: 1, email: "ada@x.io", passwordHash: "..." }, ["passwordHash"])
→ { id: 1, email: "ada@x.io" }This is how you strip secrets before sending a user object to the browser. Do not mutate the original.
- utility type
- A built-in generic type that derives a new type from an existing one, like
PartialorOmit. - Partial<T>
- Makes every property optional. The usual type for update payloads.
- Pick / Omit
- Keep only the listed keys, or keep everything except them.
- Exclude / Extract
- Remove, or keep only, the union members that match another type.
- ReturnType<F>
- The return type of a function type. Use with
typeof fnto read it off a function value. - Awaited<T>
- Unwraps a Promise type (recursively) to the value it resolves to.
- InstanceType<C>
- The type of the object
new C()produces.Cis a constructor type such astypeof MyClass. - distributive conditional type
- A conditional type on a naked type parameter, applied to each member of a union separately. Used to build
DistributiveOmit.