Generic defaults and const type parameters

Intermediate · 4 min

Default type arguments that keep generic types short to use, and `const` type parameters that infer literal types without callers writing `as const`.

Before thisGeneric constraintsReadonly and immutability

Matt Pocock · 4 min

Generic defaults and const type parameters

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Matt PocockReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A default type argument, written `<T = string>`, is used when the caller neither writes a type argument nor gives the compiler anything to infer it from.
  • Defaults matter most on generic types, where there is nothing to infer from: `ApiResponse` with defaults can be written bare, while without them every use needs every argument spelled out.
  • Inference beats defaults: for `function wrap<T = string>(value: T)`, the call `wrap(42)` infers `number` and ignores the default.
  • Type parameters with defaults must come after those without, and a default must satisfy its parameter's constraint; a later default may refer to an earlier parameter, as in `<T, U = T[]>`.
  • A `const` type parameter, added in TypeScript 5.0, makes the compiler infer literal and readonly types from the arguments as if the caller had written `as const`.
  • `const` only affects literals written directly in the call; a variable that was already widened to `string[]` stays `string[]`, and pairing `const` with a `readonly` array constraint gives the most predictable results.

Two small problems with generics

Generics so far have one cost and one gap. The cost: a generic type with several parameters is tiring to write out when most uses want the same arguments. The gap: inference widens literals, so a function that wants to know the exact strings it was given gets plain string instead. Defaults fix the first problem. const type parameters fix the second.

Default type arguments

A type parameter can name a fallback with =, the same way a function parameter can:

interface ApiResponse<TData = unknown, TError = Error> {
  data: TData | null;
  error: TError | null;
}

const r1: ApiResponse = { data: null, error: null }; // ApiResponse<unknown, Error>
const r2: ApiResponse<string[]> = { data: ["a"], error: null }; // TError is still Error

On a generic type, nothing is inferred: when you write a type annotation, every argument comes from you. Without defaults, ApiResponse alone would be an error and every annotation would need both arguments. With them, the common case is short and the unusual one is still possible. Library typings use this constantly; the no-argument overload of React’s useState is declared with S = undefined, for example.

The rules mirror optional function parameters:

type Bad<T = string, U> = [T, U];
// Error: Required type parameters may not follow optional type parameters.

type BadDefault<T extends string = number> = T;
// Error: Type 'number' does not satisfy the constraint 'string'.

type Ok<T, U = T[]> = [T, U]; // a default may refer to an earlier parameter

Type arguments are matched by position, so optional ones have to go last. A default also has to satisfy the constraint, since it stands in for a type the caller could have written.

Defaults on generic functions

On functions, a default only matters when inference has nothing to work with:

function emptyList<T = string>(): T[] {
  return [];
}

const xs = emptyList(); // string[]
const ys = emptyList<number>(); // number[]

function wrap<T = string>(value: T) {
  return { value };
}

const w = wrap(42); // { value: number }

emptyList has no parameters, so T can’t be inferred, and the default fills in. Without a default it would fall back to unknown. wrap has an argument to infer from, so the default is ignored. Treat a default as the answer to “what if nobody tells me”, not as an override.

Literal inference and as const

Now the gap. Suppose a router helper wants to know exactly which paths exist:

function routesPlain<T extends readonly string[]>(paths: T): T {
  return paths;
}

const plain = routesPlain(["/home", "/about"]); // string[]

An array literal is inferred as string[], because most of the time that’s what you want: arrays get pushed to and strings get reassigned. The caller can opt out by writing routesPlain(["/home", "/about"] as const), which gives the readonly tuple of literals. But that puts the burden on every caller, and forgetting it fails silently, since the call still compiles with the wider type.

const type parameters

TypeScript 5.0 moved that decision to the function author. Put const before the type parameter:

function routes<const T extends readonly string[]>(paths: T): T {
  return paths;
}

const r = routes(["/home", "/about"]); // readonly ["/home", "/about"]

function config<const T>(value: T): T {
  return value;
}

const cfg = config({ mode: "dark", retries: 3 });
// { readonly mode: "dark"; readonly retries: 3 }

The caller writes nothing different; the function asks for the narrowest reading of its arguments. Object literals become readonly with literal property types, and arrays become readonly tuples.

Two limits are worth knowing. First, const only affects literals written in the call:

const list = ["/home", "/about"]; // string[]
const fromVar = routes(list); // string[]

list was widened when it was declared, before routes ever saw it. Second, use a readonly array constraint. A literal inferred under const is readonly, and early versions of the feature fell back to string[] when the constraint was the mutable string[]. Newer compilers handle that case, but readonly string[] is the convention and behaves the same everywhere. It also tells callers the truth: the function doesn’t mutate their array.

About the video

Matt Pocock’s short video is about the second half of this lesson only. He shows a function where callers had to remember as const, then adds const to the type parameter and shows the literal types appear with no change at the call site. He recorded it from the pull request just before TypeScript 5.0 shipped; the feature landed as he demonstrates. Generic defaults aren’t covered there, so the sections above carry that half, and the linked two-minute tip from the same author shows defaults simplifying a real signature.

Check yourself

  1. 01In `function emptyList<T = string>(): T[]`, what is the type of `emptyList()` and why?

    It is `string[]`. The function has no parameters, so there is nothing to infer `T` from, and the compiler falls back to the default. Without the default it would fall back to `unknown`, giving `unknown[]`.

  2. 02Given `function wrap<T = string>(value: T)`, why does `wrap(42)` produce `{ value: number }` rather than an error?

    A default is only a fallback. Here the argument `42` is an inference site for `T`, so `T` is inferred as `number` and the default is never consulted.

  3. 03Why is `type Pair<T = string, U> = [T, U]` rejected?

    Required type parameters may not follow optional ones. Type arguments are matched by position, so if `T` could be left out, there would be no way to supply `U` alone. Parameters with defaults have to go at the end.

  4. 04What does `<const T extends readonly string[]>` change about the call `routes(["/home", "/about"])`?

    Without `const`, `T` is inferred as `string[]`, losing the specific paths. With it, `T` is inferred as `readonly ["/home", "/about"]`, keeping each literal and the tuple's length, exactly as if the caller had written `as const` on the argument.

  5. 05A caller does `const list = ["/home"]; routes(list);` with the `const` version of `routes`. Why does `T` come out as `string[]`?

    `const` only changes how literal expressions written in the call are inferred. `list` was already declared and widened to `string[]` before the call, so that is the type the function receives; the caller would need `as const` on the declaration to keep the literals.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark