Inference and const type parameters
You called first([8080, 9090]) in lesson 1 and never wrote <number>. TypeScript worked it out.
Most of the time that is what you want. When it picks the wrong type, you need to know why, or you
will fight the compiler instead of helping it.
Relay has a concrete case. It publishes a fixed set of topics, "job.started" and friends. If the
list is declared as an ordinary array, the names become plain string and a typo in
publish("job.statrted") compiles. This lesson fixes that.
Inference from arguments
Section titled “Inference from arguments”For each type parameter, TypeScript collects candidates from the arguments and picks one that fits all of them:
declare function pair<T>(a: T, b: T): readonly [T, T]
const p1 = pair(1, 2) // readonly [number, number]const p2 = pair("a", "b") // readonly [string, string]// @ts-expect-error: 'string' is not assignable to 'number'const p3 = pair(1, "b")Both arguments give a candidate for T. 1 and 2 agree. 1 and "b" don’t, and TypeScript
does not invent a union for you: the first candidate wins and the second argument is an error.
If you want the union, say so: pair<number | string>(1, "b").
Notice number, not 1. A literal like 1 is widened to its base type when it ends up in a
position that could be changed later:
declare function box<T>(value: T): { value: T }
const a = box(1) // { value: number }const b = box("relay") // { value: string }const c = box({ port: 8080 }) // { value: { port: number } }TypeScript assumes box(1).value may be replaced with 2, so number is the safe choice. Hold
that thought: it is the reason Relay’s topic names turn into string.
Contextual typing of callbacks
Section titled “Contextual typing of callbacks”When an argument is a function with untyped parameters, TypeScript fills them in from the type parameters it inferred from the other arguments:
declare function mapAll<A, B>(items: readonly A[], f: (item: A) => B): B[]
const ports = mapAll(["8080", "9090"], (s) => Number(s))// A is string (from the array), so `s` is string, and B is number (from the return)// ports: number[]This is why you rarely need to annotate callback parameters.
Explicit type arguments
Section titled “Explicit type arguments”Write the type arguments yourself with f<A, B>(...) when inference has nothing to work from, or
when you want a wider type than the arguments suggest:
function emptyList<T>(): T[] { return []}
const a = emptyList() // unknown[]: nothing to infer fromconst b = emptyList<string>() // string[]
const wide = new Set<string | number>([1, 2]) // Set<string | number>, not Set<number>When inference fails, TypeScript falls back to the constraint, which is unknown if there is none.
A result of unknown[] or unknown is the sign that the type parameter had no candidates. Fix
it by giving it one: an argument, a callback, or an explicit type argument.
Keeping literals: const type parameters
Section titled “Keeping literals: const type parameters”Here is Relay’s topic list:
function defineTopics<T extends readonly string[]>(names: T): T { return names}
const topics = defineTopics(["job.started", "job.failed"])// string[] (widened: the array could be changed later)The caller can make the compiler keep the literals with as const:
declare function defineTopics<T extends readonly string[]>(names: T): T
const topics = defineTopics(["job.started", "job.failed"] as const)// readonly ["job.started", "job.failed"]That works until someone forgets as const, and then the types quietly become string with no
error. Put the requirement in the function instead. A const type parameter (TypeScript 5.0)
tells inference to treat the argument as if it had as const:
declare function defineTopics<const T extends readonly string[]>(names: T): T
const topics = defineTopics(["job.started", "job.failed"])// readonly ["job.started", "job.failed"]
type Topic = (typeof topics)[number] // "job.started" | "job.failed"
function publish(topic: Topic) {}publish("job.started")// @ts-expect-error: '"job.statrted"' is not assignable to type 'Topic'publish("job.statrted")Two details. Write the constraint as readonly string[], not string[]: a mutable constraint
rejects readonly arguments, such as an array declared with as const. And const also works on
a single string: <const P extends string>(path: P) keeps "/webhooks" as is, without needing
the caller to write a type annotation.
Exercise
Section titled “Exercise”Relay declares its topics once and routes webhooks by path. Add const to the type parameters so
the topic names and path literals survive, and use T[number] for the name type.
- Inference collects candidates from the arguments. Conflicting candidates are an error, not a union.
- Literals are widened to
stringornumberin positions that could change. - Callback parameters are typed from the other arguments.
- Inference that finds nothing gives
unknown. Add an argument or write the type argument. <const T extends readonly string[]>keepsreadonly ["a", "b"]without asking callers foras const.
Further reading
Section titled “Further reading”- TypeScript 5.0 release notes:
consttype parameters. - TypeScript 5.4 release notes: the
NoInferutility type. - Handbook: More on Functions: inference and contextual typing.