Sub topic 12
Writing your own utility types
The built-in utility types cover common cases. Eventually you will need a shape they do not provide: "make only these two keys optional", "find the keys whose values are strings", or "make everything readonly, all the way down". This chapter shows how to write those types yourself.
This chapter assumes you know generics, keyof, indexed access types (T[K]), and the mapped-type syntax { [K in keyof T]: ... } from the earlier chapters. It also assumes you know conditional types in the form A extends B ? X : Y.
The three building blocks
Almost every custom utility type combines three tools:
- Mapped types loop over keys and produce a new object type.
- Conditional types choose between two outcomes based on a type test.
- Composition of existing utilities, using
Omit,Pick,Partialand intersections.
Start with composition. If a built-in combination already gives the result you want, a named alias is the cheapest custom utility. Reach for a mapped type when you need to change every property in the same way. Reach for a conditional type when the result depends on what each property's type is.
Composition: PartialBy and RequiredBy
Partial<T> makes every property optional. Often you want only some keys optional. Combine Omit and Pick:
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 Account {
id: number;
name: string;
email?: string;
nickname?: string;
}
// id becomes optional; everything else is unchanged.
type AccountDraft = PartialBy<Account, "id">;
// email becomes mandatory.
type ContactableAccount = RequiredBy<Account, "email">;
const draft: AccountDraft = { name: "Ada" };
const contact: ContactableAccount = { id: 1, name: "Ada", email: "[email protected]" };
console.log(draft, contact);The constraint K extends keyof T makes PartialBy<Account, "idd"> a compile error, which is the main reason to write the utility as a generic instead of retyping the object.
The result is an intersection (A & B). It behaves correctly, but editor hover text shows the intersection instead of one flat object. A small helper flattens it:
type Simplify<T> = { [K in keyof T]: T[K] } & {};
type PartialBy<T, K extends keyof T> = Simplify<Omit<T, K> & Partial<Pick<T, K>>>;Hovering over a PartialBy<Account, "id"> now shows the merged properties. The & {} stops the compiler from displaying the alias name instead of the expanded shape.
Mapped types that change modifiers
The built-in Readonly<T> adds the readonly modifier. There is no built-in inverse, but the - prefix removes a modifier:
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type Nullable<T> = { [K in keyof T]: T[K] | null };
interface Point {
readonly x: number;
readonly y: number;
}
const p: Mutable<Point> = { x: 0, y: 0 };
p.x = 10; // allowed: readonly was removed
const maybe: Nullable<Point> = { x: null, y: 5 };
console.log(p, maybe);Mapped types of the form [K in keyof T] are called homomorphic. They copy the optional and readonly modifiers from T unless you override them with ?, -?, readonly or -readonly. This is why Nullable<Point> keeps x and y readonly.
Choosing keys by value type
Built-in Pick selects by key name. Sometimes you want to select by value type, for example "all keys whose values are strings". Do this in two steps: map each key to either itself or never, then index the result with keyof T, which collapses the never entries away.
type KeysOfType<T, V> = {
[K in keyof T]-?: T[K] extends V ? K : never;
}[keyof T];
interface Product {
id: number;
name: string;
sku: string;
price: number;
tags?: string[];
}
type StringKeys = KeysOfType<Product, string>; // "name" | "sku"
type NumberKeys = KeysOfType<Product, number>; // "id" | "price"
type StringFields = Pick<Product, StringKeys>; // { name: string; sku: string }
const fields: StringFields = { name: "Lamp", sku: "L-100" };
console.log(fields);The -? matters. Without it, an optional property such as tags contributes undefined to the final union, because indexing an object with optional properties includes undefined in the result. With -?, only the key names remain.
Renaming keys with `as`
Since TypeScript 4.1, a mapped type can rewrite each key with an as clause. Combined with template literal types, this builds derived APIs:
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
interface Person {
name: string;
age: number;
}
type PersonGetters = Getters<Person>;
// { getName: () => string; getAge: () => number }
const getters: PersonGetters = {
getName: () => "Ada",
getAge: () => 36,
};
console.log(getters.getName(), getters.getAge());keyof T & string keeps only string keys. Template literal types cannot interpolate symbol, and keyof T may include one.
If the as clause produces never for a key, that key is dropped. This gives you a second way to filter properties:
type OmitByType<T, V> = {
[K in keyof T as T[K] extends V ? never : K]: T[K];
};
interface Row {
id: number;
label: string;
active: boolean;
}
type NoStrings = OmitByType<Row, string>; // { id: number; active: boolean }Recursion: DeepPartial and DeepReadonly
Partial<T> only affects the top level. A recursive type applies the same transformation to nested objects. The base case matters: without it, the type walks into primitives, functions and dates, and produces odd results.
type DeepPartial<T> = T extends string | number | boolean | bigint | symbol | null | undefined
? T
: T extends (...args: any[]) => unknown
? T
: T extends Date
? T
: { [K in keyof T]?: DeepPartial<T[K]> };
interface Config {
server: { host: string; port: number; tls: { cert: string; key: string } };
retries: number;
tags: string[];
createdAt: Date;
}
const override: DeepPartial<Config> = {
server: { tls: { cert: "cert.pem" } },
tags: ["a", "b"],
};
console.log(override);Because DeepPartial<T> is a conditional type whose checked type is the bare parameter T, it distributes over unions. A property of type string | Date is handled one member at a time. Arrays also work: a homomorphic mapped type applied to an array type produces an array, so tags stays string[] (its elements are mapped too, and DeepPartial<string> is string).
DeepReadonly follows the same pattern with readonly in place of ?:
type DeepReadonly<T> = T extends string | number | boolean | bigint | symbol | null | undefined
? T
: T extends (...args: any[]) => unknown
? T
: { readonly [K in keyof T]: DeepReadonly<T[K]> };Distributive helpers
Omit does not distribute over unions. The fix from the previous chapter is a conditional type, and the same trick applies to your own utilities:
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown
? Omit<T, K>
: never;
type DistributivePick<T, K extends PropertyKey> = T extends unknown
? Pick<T, K & keyof T>
: never;T extends unknown is always true. Its only job is to make TypeScript apply the right-hand side to each member of the union separately. DistributivePick intersects K with keyof T so that a key missing from one union member does not cause an error for that member.
Testing a type
Types have no runtime tests, so a mistake only shows up when someone uses the type. You can pin down the expected result with compile-time assertions:
type Equal<A, B> =
(<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
type Expect<T extends true> = T;
type KeysOfType<T, V> = {
[K in keyof T]-?: T[K] extends V ? K : never;
}[keyof T];
interface Product {
id: number;
name: string;
sku: string;
tags?: string[];
}
type Test1 = Expect<Equal<KeysOfType<Product, string>, "name" | "sku">>;
type Test2 = Expect<Equal<KeysOfType<Product, number>, "id">>;
// type Test3 = Expect<Equal<KeysOfType<Product, number>, "id" | "name">>; // compile errorIf the types differ, Equal yields false, and Expect<false> fails to compile. Run tsc --noEmit and the file doubles as a test suite for your utilities. This Equal form is stricter than a plain mutual-assignability check, which treats any and some intersections as equal to other types.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Optional keys leak `undefined` into a key union | Mapped type used without `-?` before indexing with `[keyof T]` | Add `-?` to the mapped type |
| `DeepPartial` makes `Date` or methods strange | No base case for non-plain objects | Return `T` unchanged for functions, dates and primitives |
| A union collapses to its shared keys | Utility such as `Omit` applied to a union without distribution | Wrap it in `T extends unknown ? ... : never` |
| "Type instantiation is excessively deep" | Recursive type applied to a cyclic or very large type | Add a depth limit or stop recursion at known types |
| Template literal key errors | `keyof T` includes `number` or `symbol` | Use `keyof T & string` |
| Hover text shows `A & B` | Intersection is not flattened | Wrap the result in `Simplify` |
When to stop
A custom utility type is worth writing when the same derivation appears in several places, or when a derivation keeps a type in sync with its source (keyof, mapped types and Pick all do). It is not worth it when a type is used once, or when the generic form is harder to read than the plain object type it replaces. If a teammate must study the utility to understand a function signature, a plain interface is usually the better choice.
Exercise
Write a utility type RequiredKeys<T> that produces the union of keys of T that are NOT optional. For interface Item { id: number; label: string; note?: string }, RequiredKeys<Item> should be "id" | "label".
Show answer
Map each key to itself if the property is required, otherwise to never, then index with keyof T. A property is optional exactly when {} is assignable to Pick<T, K>.
type RequiredKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? never : K;
}[keyof T];
interface Item { id: number; label: string; note?: string }
type R = RequiredKeys<Item>; // "id" | "label"
For note, Pick<Item, "note"> is { note?: string }, and {} is assignable to it, so the key becomes never. For id, {} is not assignable to { id: number }, so the key is kept. The -? prevents undefined from appearing in the final union.