Conditional types and infer
Relay’s pipeline helpers keep asking the same question: what is inside this type? The value inside
a Promise, the value inside a Result, the argument a handler takes. Today the answer is a cast:
(await job) as JobOutput. When the job’s type changes, the cast still compiles and the bug moves
to runtime.
A conditional type asks the question in the type system and returns the answer. When a library function’s return type “depends on the input type”, a conditional type is almost always behind it.
T extends U ? X : Y
Section titled “T extends U ? X : Y”A conditional type picks one of two types. If T is assignable to U, the result is X,
otherwise Y:
type IsString<T> = T extends string ? true : false
type A = IsString<"hello"> // truetype B = IsString<number> // false
type Method = "GET" | "POST"type HasBody<M extends Method> = M extends "POST" ? true : falsetype PostBody = HasBody<"POST"> // truetype GetBody = HasBody<"GET"> // falseThe check is the same one as assignment: "hello" is assignable to string, so the first branch
wins. It runs at compile time and costs nothing at runtime.
infer: name a part and use it
Section titled “infer: name a part and use it”The useful form puts infer inside the extends side. It says: if T has this shape, call the
piece in that position V and let me use it in the result branch:
type Unwrap<P> = P extends Promise<infer V> ? V : P
type A = Unwrap<Promise<number>> // numbertype B = Unwrap<string> // string: not a Promise, so it stays as it istype C = Unwrap<Promise<Promise<number>>> // Promise<number>: only one levelUnwrap is a one-level version of the built-in Awaited. The : P branch is the “otherwise”
case. Pick it on purpose. Returning P means “leave it alone”, returning never means “this is
an error, no value exists”.
Reading arrays, results and functions
Section titled “Reading arrays, results and functions”The same shape works for anything with a position to pull from. Arrays give their element type.
M3’s Result (lesson 1) gives its value or its error. A function gives its
parameters and return type:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }
type ElementOf<T> = T extends readonly (infer U)[] ? U : nevertype ResultValue<R> = R extends { readonly ok: true; readonly value: infer V } ? V : nevertype ResultError<R> = R extends { readonly ok: false; readonly error: infer E } ? E : never
type Parsed = Result<{ readonly source: string }, "InvalidJson">type Value = ResultValue<Parsed> // { readonly source: string }type Error = ResultError<Parsed> // "InvalidJson"type Item = ElementOf<readonly string[]> // stringtype NotArray = ElementOf<number> // neverResultValue<Parsed> reaches { ok: true; ... } through a union. A conditional type on a union
is applied to each member and the results are joined: the failure member gives never, which
disappears. Lesson 2 explains this rule and its traps.
A function type gives up its first parameter:
type HandlerInput<H> = H extends (input: infer I, ...rest: never[]) => unknown ? I : never
type FailedHandler = (event: { readonly jobId: string; readonly reason: string }) => voidtype Input = HandlerInput<FailedHandler> // { readonly jobId: string; readonly reason: string }Parameters and ReturnType, which M3 used, are built exactly like this. Lesson 6
writes them.
Use them in a signature
Section titled “Use them in a signature”A conditional type is most useful when a function’s signature needs it. A fallback for a Result
should have the success type of that result:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }type ResultValue<R> = R extends { readonly ok: true; readonly value: infer V } ? V : never
function valueOr<R extends Result<unknown, unknown>>(result: R, fallback: ResultValue<R>): ResultValue<R>function valueOr(result: Result<unknown, unknown>, fallback: unknown): unknown { return result.ok ? result.value : fallback}
declare const parsed: Result<number, string>const n = valueOr(parsed, 0) // number// @ts-expect-error: 'string' is not assignable to 'number'valueOr(parsed, "none")Why two signatures? Inside a generic function, TypeScript treats ResultValue<R> as an unresolved
question and will not let result.value satisfy it. The first signature is the contract callers
see. The second is the implementation, written with plain types. TypeScript checks that the two
are compatible, but it cannot check the body against the contract, so keep the body small and test
it.
Exercise
Section titled “Exercise”Relay’s helpers currently return unknown for all of these questions. Write Unwrap,
ElementOf, ResultValue, ResultError and HandlerInput, then use them in the signatures of
valueOr and callHandler. The tests check the types, so run tsc as you go.
T extends U ? X : Yis anifon types. It uses the same assignability check as any assignment.infer Vinside theextendsside names a part ofTand makes it available in the result.- The false branch is a choice: return the input to leave it alone, or
neverfor “no answer”. - A conditional type applied to a union runs per member. Lesson 2 covers it.
- Inside generic functions the compiler can’t resolve a conditional type. Declare the contract with an overload and keep the implementation simple.
- Prefer a plain generic when it says the same thing: errors are shorter.
Further reading
Section titled “Further reading”- Conditional Types:
inferand distribution. - TypeScript 4.5: tail-recursion elimination and
Awaited.