Sub topic 8
Rebuilding the built-in utility types
This chapter assumes you know how mapped types ({ [K in keyof T]: ... }), conditional types (T extends U ? X : Y), and infer work, and that you are comfortable with generic constraints. Here you use those pieces to write your own versions of the standard utility types. Each My version below behaves like the built-in one. Building them shows you what the built-ins do and where they stop.
Why rebuild them
The utility types in lib.d.ts are ordinary type aliases. They use no special compiler feature. Reading their definitions, or writing your own, tells you three things:
- Which utilities are mapped types and which are conditional types.
- Which constraints they put on their parameters, and what those constraints allow.
- Why some utilities behave in surprising ways on unions and generic functions.
The utilities fall into three groups, shown below.
Utilities built from mapped types
Three utilities change only the modifiers of a type. Each is a homomorphic mapped type: it iterates keyof T directly, so the result keeps the original optionality and readonly flags unless you change them.
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyRequired<T> = { [K in keyof T]-?: T[K] };
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };-? does more than mark the property as required. It also strips undefined from the property type, which Required relies on:
type Opts = { a?: string | undefined; b: number };
type R = MyRequired<Opts>;
// { a: string; b: number }(With exactOptionalPropertyTypes enabled, an explicit | undefined stays. This is one of the few places where that flag changes the result.)
Pick and Record do not iterate keyof T. They iterate a set of keys you supply:
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };
type MyRecord<K extends keyof any, T> = { [P in K]: T };The constraints matter:
- In
MyPick,K extends keyof Tlets the compiler treat[P in K]as homomorphic. SoPickcopiesreadonlyand?fromT. Passing a key thatTlacks is an error. - In
MyRecord,Khas no relationship to any source type, so there are no modifiers to copy.keyof anyisstring | number | symbol, the set of valid property keys.
type User = { readonly id: number; name?: string; email: string };
type IdAndName = MyPick<User, "id" | "name">;
// { readonly id: number; name?: string }
type Roles = MyRecord<"admin" | "guest", boolean>;
// { admin: boolean; guest: boolean }
type Lookup = MyRecord<string, number>;
// { [x: string]: number }Utilities built from conditional types
Exclude and Extract are distributive conditional types. The type parameter T stands alone before extends, so the check runs once for each member of a union and the results are joined back together:
type MyExclude<T, U> = T extends U ? never : T;
type MyExtract<T, U> = T extends U ? T : never;
type Letters = "a" | "b" | "c";
type NoA = MyExclude<Letters, "a">; // "b" | "c"
type OnlyAB = MyExtract<Letters, "a" | "b">; // "a" | "b"The mechanism is that never is an empty union. Each member that fails the filter turns into never, and never disappears when joined with other members.
NonNullable removes null and undefined. The classic definition is a conditional type:
type MyNonNullable<T> = T extends null | undefined ? never : T;
type Name = MyNonNullable<string | null | undefined>; // stringCurrent versions of TypeScript define the built-in as T & {} instead. The result for unions is the same, because {} excludes null and undefined, and the intersection form is cheaper for the compiler. Either way you can read it as a filter.
Omit: combining the two groups
Omit removes keys. It picks every key of T except the ones you name:
type MyOmit<T, K extends keyof any> = MyPick<T, MyExclude<keyof T, K>>;
type PublicUser = MyOmit<User, "email">;
// { readonly id: number; name?: string }The built-in Omit has the same shape, and that shape has two consequences.
First, K extends keyof any accepts any key, even one that T does not have. A typo in the key silently removes nothing:
type Oops = MyOmit<User, "emial">; // no error; email is still presentIf you want errors on typos, write a stricter version with K extends keyof T.
Second, Omit does not distribute over unions. keyof (A | B) is only the keys common to both members, so the union collapses:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
type Bad = MyOmit<Shape, "kind">; // {}The fix is to add a distributive wrapper:
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown
? MyOmit<T, K>
: never;
type Good = DistributiveOmit<Shape, "kind">;
// { radius: number } | { side: number }Utilities built from infer
The function utilities use infer to capture part of a function type. The extends (...args: any) => any constraint on the parameter rejects non-function types.
type MyParameters<T extends (...args: any) => any> =
T extends (...args: infer P) => any ? P : never;
type MyReturnType<T extends (...args: any) => any> =
T extends (...args: any) => infer R ? R : any;
type MyInstanceType<T extends abstract new (...args: any) => any> =
T extends abstract new (...args: any) => infer R ? R : any;Here is how they behave on a concrete function and class:
function connect(host: string, port?: number): { open: boolean } {
return { open: host.length > 0 && (port ?? 0) >= 0 };
}
class Client {
constructor(public url: string) {}
}
type ConnectArgs = MyParameters<typeof connect>;
// [host: string, port?: number | undefined]
type ConnectResult = MyReturnType<typeof connect>;
// { open: boolean }
type ClientInstance = MyInstanceType<typeof Client>;
// ClientMyParameters returns a tuple, so labels and optional elements are preserved. Because infer P sits in a rest position, the compiler infers the whole parameter list as one tuple.
Three limits are worth knowing:
- For an overloaded function, inference uses the last overload signature only.
- For a generic function, type parameters are replaced by their constraints.
MyReturnType<<T>(x: T) => T>givesunknown. typeof Clientis needed for classes because the class name alone refers to the instance type.abstract newin the constraint also accepts abstract classes.
Checking your versions against the built-ins
You can test a rebuilt type at compile time. This helper reports true only when two types are identical, not merely assignable to each other:
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 MyPartial<T> = { [K in keyof T]?: T[K] };
type MyExclude<T, U> = T extends U ? never : T;
type MyReturnType<T extends (...args: any) => any> =
T extends (...args: any) => infer R ? R : any;
type Person = { id: number; name: string };
type Checks = [
Expect<Equal<MyPartial<Person>, Partial<Person>>>,
Expect<Equal<MyExclude<"a" | "b" | "c", "a">, Exclude<"a" | "b" | "c", "a">>>,
Expect<Equal<MyReturnType<() => number>, ReturnType<() => number>>>
];If any check were false, Expect would raise a compile error on that line. Run tsc --noEmit on the file to see the result. This is a lightweight way to test type-level code, since there is no runtime to execute.
Summary table
| Utility | Built from | Key point |
|---|---|---|
| `Partial`, `Required`, `Readonly` | Homomorphic mapped type with `?`, `-?`, `readonly` | Keeps other modifiers; `-?` also removes `undefined` |
| `Pick` | Mapped type over `K extends keyof T` | Copies modifiers; rejects unknown keys |
| `Record` | Mapped type over any key set | No source type, so no modifiers |
| `Exclude`, `Extract` | Distributive conditional type | Filters union members using `never` |
| `NonNullable` | Conditional type (or `T & {}`) | Removes `null` and `undefined` |
| `Omit` | `Pick` plus `Exclude` | Accepts any key; does not distribute |
| `Parameters`, `ReturnType`, `InstanceType` | Conditional type with `infer` | Overloads use the last signature; generics collapse to constraints |
Common errors
- Using
Omiton a union. The result loses member-specific properties. Use a distributive version. - Expecting
Record<string, T>to behave like an object type. It is an index signature, so every key lookup is allowed and typed asT. - Constraining
ReturnTypeinput badly. Passing a function value instead of its type gives an error. WriteReturnType<typeof fn>. - Assuming
Requiredonly flips?. It also removesundefinedfrom the property type, which can hide intendedundefinedvalues.
Exercise
Write StrictOmit<T, K extends keyof T> so that a typo in the key list is a compile error, and explain why StrictOmit<User, "emial"> fails while the built-in Omit<User, "emial"> does not.
Show answer
type StrictOmit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; The constraint K extends keyof T limits K to keys that exist on T, so "emial" is not assignable and the compiler reports an error. The built-in Omit constrains K only to keyof any (string | number | symbol), so any key is accepted and a misspelled one simply removes nothing.
Exercise
Define MyAwaitedOnce<T> that unwraps one level of Promise using infer, returning T unchanged if it is not a promise. What is MyAwaitedOnce<Promise<Promise<number>>>?
Show answer
type MyAwaitedOnce<T> = T extends Promise<infer U> ? U : T; The result is Promise<number>, because only one layer is unwrapped. Making the helper refer to itself in the true branch (MyAwaitedOnce<U>) would unwrap every layer and give number.