Generic functions
Relay now calls a queue, an upstream API and a notifier. Every call can fail, and every call returns
a different type. M2’s result union was written for one thing, JobEvent. Copying it for each
service means three unions that differ in one word each.
This module builds machinery that works for any type and keeps the type the caller had. The tool is the type parameter. This lesson covers functions and type aliases. Classes come in lesson 4.
The problem with unknown
Section titled “The problem with unknown”The quick way to share code between types is unknown. It accepts everything, and it forgets
everything:
function first(xs: readonly unknown[]): unknown { return xs[0]}
const port = first([8080, 9090])// @ts-expect-error: 'port' is of type 'unknown'port.toFixed()const n = port as number // a cast: nothing checks itThe function took numbers and gave back “something”. The caller has to cast, and the cast is a promise the compiler can’t check. Relay’s fix is not a looser type. It is a type that relates the input to the output.
A type parameter
Section titled “A type parameter”A type parameter is a type the caller fills in. Write it in angle brackets before the parameters:
function identity<T>(value: T): T { return value}
const a = identity(42) // T is numberconst b = identity("relay") // T is string
function first<T>(xs: readonly T[]): T | undefined { return xs[0]}
const port = first([8080, 9090]) // number | undefinedconst none = first([]) // undefinedfirst makes one promise: whatever type of element goes in comes out. It doesn’t know what T
is, so inside the body it can’t do anything with a T that works for every type. It can return
it, store it and pass it on. That’s why it is safe for all callers. How TypeScript picks T is
lesson 2.
Generic type aliases
Section titled “Generic type aliases”Type aliases take parameters too. Here is M2’s result union with the event type pulled out as A,
and the error type as E:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }
declare const r: Result<number, Error>if (r.ok) { r.value // number} else { r.error // Error}ok is still the discriminant, so narrowing works as in M2. Most failures in Relay
are Error, so give E a default:
type Result<A, E = Error> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }
declare const r: Result<string> // same as Result<string, Error>A default works like a default argument: it is used when the caller doesn’t write that parameter. Parameters with defaults go after those without.
Constructors and never
Section titled “Constructors and never”Two small functions build results:
type Result<A, E = Error> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }
const ok = <A>(value: A): Result<A, never> => ({ ok: true, value })const err = <E>(error: E): Result<never, E> => ({ ok: false, error })
const good: Result<number, SyntaxError> = ok(1)const bad: Result<number, SyntaxError> = err(new SyntaxError("x"))ok(1) has no error to report, so its error type is never, the type with no values (see
unknown and never). never is assignable to every type, so Result<number, never>
fits anywhere a Result<number, E> is expected, for any E. The same is true of err and the
value type. A function that returns either one can have a return type of Result<number, Error>,
and both branches type-check.
Constraints
Section titled “Constraints”Sometimes the function does need to know something about T. Say so with extends:
function indexById<T extends { readonly id: string }>(items: readonly T[]): Map<string, T> { const index = new Map<string, T>() for (const item of items) index.set(item.id, item) return index}
interface Job { readonly id: string readonly queuedAt: number}declare const jobs: readonly Job[]
const byId = indexById(jobs) // Map<string, Job>// @ts-expect-error: Property 'id' is missingindexById([{ name: "x" }])T extends { readonly id: string } means “any type at least this wide”. Inside the body you can
read item.id. The result is Map<string, Job>, not Map<string, { id: string }>: the constraint
limits what callers may pass, and T still remembers what they did pass.
A type parameter must earn its place
Section titled “A type parameter must earn its place”A type parameter is useful when it relates things: an input to an output, or two inputs to each other. A parameter that appears once relates nothing:
// T appears once: this is just (x: unknown) => void with more syntaxfunction log<T>(x: T): void { console.log(x)}
// T appears only in the return type: the caller picks it and nothing checks itfunction parse<T>(text: string): T { return JSON.parse(text)}
const n = parse<number>('"not a number"') // compiles, and is a string at runtimeparse<number> is a cast with extra steps. The compiler believes whatever the caller writes. The
honest version takes something that produces the T, such as a function that checks the data:
function parse<A>(text: string, check: (data: unknown) => A): A { return check(JSON.parse(text))}
const port = parse("8080", (d) => { if (typeof d !== "number") throw new Error("port must be a number") return d}) // numberNow A appears in the callback’s return and in the result, so it is tied to real code. Rule of
thumb: if a type parameter appears once, remove it. If it appears only in the return type, ask where
the value really comes from.
Naming
Section titled “Naming”Tfor one unremarkable type.Uif you need a second.AandEfor a result’s value and error,KandVfor keys and values.- Several parameters with real meaning: use names.
<Event, State>reads better than<T, U>.
Exercise
Section titled “Exercise”Relay’s Result and its helpers are typed with unknown and any, so every caller must cast.
Make them generic. tryParse needs a parse function, for the reason in the last section.
unknownforgets types. A type parameter passes the caller’s type through to the result.- Aliases take parameters, and parameters can have defaults:
Result<A, E = Error>. okreturnsResult<A, never>anderrreturnsResult<never, E>.nevermakes each fit anyResult.T extends Shapelimits what callers may pass and lets the body useShape.Tstays the caller’s full type.- A type parameter should appear at least twice. One that appears only in the return type is a cast.
Further reading
Section titled “Further reading”- Handbook: Generics: type parameters and constraints.
- Handbook: More on Functions: generic functions and inference.