Re-implementing the built-in utility types
Relay’s config overrides use Partial<Config>. The retry helper takes Pick<Options, "attempts">.
ReturnType and Awaited appear in half of M3. They look like language features, so when one gives
a strange result there is nothing to look at.
They are ordinary type aliases, built from the tools in lessons 1 to 3: mapped types for the ones that reshape objects and conditional types for the ones that filter or read. Write them once and the built-ins stop being magic. You can also write your own when the built-in is not quite right.
Mapped types: reshape an object
Section titled “Mapped types: reshape an object”Four of them only change the property list or its modifiers:
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] }type MyPick<T, K extends keyof T> = { [P in K]: T[P] }
interface Options { readonly name: string timeoutMs?: number}type Patch = MyPartial<Options> // { readonly name?: string; timeoutMs?: number }type Full = MyRequired<Options> // { readonly name: string; timeoutMs: number }type OnlyName = MyPick<Options, "name"> // { name: string }MyPick loops over K, not keyof T, and the constraint K extends keyof T is what makes
T[P] legal. It is also why Pick<Options, "nope"> is an error. MyPick keeps readonly and ?
too: TypeScript copies the modifiers when the keys are constrained by keyof T.
Record is the same without the source object:
type MyRecord<K extends PropertyKey, V> = { [P in K]: V }
type Tag = "WebhookReceived" | "JobQueued" | "JobFailed"type Counts = MyRecord<Tag, number> // { WebhookReceived: number; JobQueued: number; JobFailed: number }Conditional types: filter a union
Section titled “Conditional types: filter a union”Exclude and Extract are the two filters from lesson 2. NonNullable
is Exclude with a fixed second argument:
type MyExclude<T, U> = T extends U ? never : Ttype MyExtract<T, U> = T extends U ? T : nevertype MyNonNullable<T> = T extends null | undefined ? never : T
type A = MyExclude<"a" | "b" | "c", "a" | "b"> // "c"type B = MyExtract<string | number | null, string | number> // string | numbertype C = MyNonNullable<string | null | undefined> // stringOmit combines both families. Take the keys of T, filter out the unwanted ones, pick what is
left:
type MyExclude<T, U> = T extends U ? never : Ttype MyPick<T, K extends keyof T> = { [P in K]: T[P] }type MyOmit<T, K extends PropertyKey> = MyPick<T, MyExclude<keyof T, K>>
interface Options { readonly name: string timeoutMs?: number label?: string}type NoLabel = MyOmit<Options, "label"> // { readonly name: string; timeoutMs?: number }type Unchanged = MyOmit<Options, "nope"> // still all three keysK extends PropertyKey and not keyof T is the reason Omit<Options, "nope"> is accepted. It is
a known looseness: a typo in an Omit is silent, where a typo in a Pick is an error. A stricter
Omit<T, K extends keyof T> is easy to write, and a good fit for code you own.
infer: read a function
Section titled “infer: read a function”ReturnType and Parameters use infer (lesson 1) on a function type.
Parameters captures the whole parameter list as a tuple:
type MyReturnType<F extends (...args: never) => unknown> = F extends (...args: never) => infer R ? R : nevertype MyParameters<F extends (...args: never) => unknown> = F extends (...args: infer P) => unknown ? P : never
declare function enqueue(kind: string, delayMs: number, urgent?: boolean): Promise<string>
type Ret = MyReturnType<typeof enqueue> // Promise<string>type Args = MyParameters<typeof enqueue> // [kind: string, delayMs: number, urgent?: boolean]The constraint (...args: never) => unknown accepts every function. It uses never for the
arguments because any function is assignable to a function that cannot be called with anything.
That is one way to say “any function” without any. The built-in ReturnType is declared with
(...args: any) => any instead.
Recursion: Awaited
Section titled “Recursion: Awaited”Awaited is the one that calls itself. A promise may contain a promise, so unwrap until a plain
value is left:
type MyAwaited<T> = T extends PromiseLike<infer V> ? MyAwaited<V> : T
type A = MyAwaited<Promise<Promise<number>>> // numbertype B = MyAwaited<string> // stringtype C = MyAwaited<Promise<string> | number> // string | numberLesson 1’s Unwrap stopped after one level. This keeps going because the result is passed back
into the same type. Lesson 5 uses the same idea on objects. The real Awaited
also treats null, undefined and objects with a then method with extra care, which is the part
to read in the TypeScript source when you need exact behavior.
Exercise
Section titled “Exercise”Implement all twelve types. Each is one line in the previous sections. The tests compare your type
to the built-in on Relay’s Config and RelayEvent, so a type that almost works still fails. Two
small functions, override and pickKeys, make the file runnable and show the types in use.
Partial,Required,Readonly,PickandRecordare mapped types. Only the modifiers and the key list change.Exclude,ExtractandNonNullableare distributive conditional types that returnneverto drop a member.OmitisPickoverExclude<keyof T, K>. ItsKis loose on purpose.ReturnTypeandParametersareinferon a function type, with(...args: never) => unknownas the “any function” constraint.Awaitedis recursive: it applies itself to what it unwrapped.- Reach for the built-in first. Write your own when you need a stricter or deeper variation.
Further reading
Section titled “Further reading”- Utility Types: the built-in utility types this lesson rebuilds.
- Mapped Types: the
asclause and modifiers. - TypeScript 4.5: tail-recursion elimination and
Awaited.