Sub topic 10
Const type parameters in generic functions
Earlier chapters used as const at the place where a value is written. This chapter moves the same behavior into a function's signature. With a const type parameter, callers get literal, readonly inference without having to write as const themselves. The feature needs TypeScript 5.0 or later.
What this chapter assumes
You should already know:
- how literal widening works and what
as constdoes to objects and arrays - how to derive a union with
(typeof VALUE)[number] - how readonly tuples differ from mutable arrays in assignability
- how to write a basic generic function with an
extendsconstraint
If any of these is shaky, review the earlier chapters first. The examples build directly on them.
The problem: generic inference widens arguments
When you pass an array literal to a generic function, TypeScript infers the type parameter from the argument. It applies the same widening rules you saw for let variables. Nothing in the call marks the literal as something to preserve, so it widens.
function tupleLoose<T extends readonly unknown[]>(items: T): T {
return items;
}
const a = tupleLoose(["a", 1]);
// (string | number)[]
const b = tupleLoose(["a", 1] as const);
// readonly ["a", 1]The second call works, but it puts a burden on every caller. Anyone who forgets as const silently gets the wide type. For a function designed to capture exact values, that is easy to get wrong and hard to notice.
The function author knows the function needs literal types, but the plain signature gives no way to say so. The const modifier on the type parameter fixes this.
The `const` modifier
Write const before the type parameter name:
function tuple<const T extends readonly unknown[]>(items: T): T {
return items;
}
const t = tuple(["a", 1]);
// readonly ["a", 1]The caller wrote a plain array literal. The compiler inferred T as if the argument were written ["a", 1] as const. The modifier changes how T is inferred from literal expressions in the call, and it does not change the function's runtime code.
The compiled JavaScript has no trace of const. The returned array is an ordinary mutable array at runtime, exactly as it is with a plain as const.
How the compiler decides
The modifier affects only inference from literal expressions written directly in the argument position. The flowchart shows the decision.
Two branches deserve attention: the variable case and the constraint fallback. The next sections cover both.
Objects and nested values
The modifier applies deeply, just like as const. Object properties become readonly with literal types, and nested arrays become readonly tuples.
function defineConfig<const T extends { mode: string; retries: number }>(
config: T,
): T {
return config;
}
const cfg = defineConfig({ mode: "dark", retries: 3 });
// { readonly mode: "dark"; readonly retries: 3 }Without the const modifier, the inferred type is { mode: string; retries: number }. The constraint only says what shapes are acceptable. It does not make the compiler keep the literals.
Now a nested case. A route table is a good fit because you usually want to derive a union of paths or methods from it:
type Route = { path: string; method: "GET" | "POST" };
function defineRoutes<const T extends readonly Route[]>(routes: T): T {
return routes;
}
const routes = defineRoutes([
{ path: "/users", method: "GET" },
{ path: "/users", method: "POST" },
]);
// readonly [
// { readonly path: "/users"; readonly method: "GET" },
// { readonly path: "/users"; readonly method: "POST" }
// ]
type Path = (typeof routes)[number]["path"];
// "/users"
type Method = (typeof routes)[number]["method"];
// "GET" | "POST"
// defineRoutes([{ path: "/x", method: "PUT" }]);
// error: Type '"PUT"' is not assignable to type '"GET" | "POST"'Two things happen in one call. The constraint readonly Route[] validates the shape, so the "PUT" call fails. The const modifier keeps the exact literals, so the derived Path and Method unions are precise.
You have seen this combination before as as const satisfies readonly Route[]. Here the function signature does the same job once, for every caller.
Deriving unions without writing `as const`
The most common use is a helper that defines a list of allowed values. Callers pass a plain array, and both the runtime list and the type come from it:
function defineRoles<const T extends readonly string[]>(roles: T): T {
return roles;
}
const ROLES = defineRoles(["admin", "editor", "viewer"]);
type Role = (typeof ROLES)[number];
// "admin" | "editor" | "viewer"Compare this with the earlier pattern, const ROLES = [...] as const. The result is the same, but the convention now lives in one function instead of in the memory of every developer.
If you add the constraint readonly string[], the function also rejects non-string entries at the call site. A plain as const array accepts anything.
Where the modifier does nothing: variables
The modifier is not retroactive. If the argument is a variable, its type was fixed when the variable was declared:
const raw = ["a", 1];
// (string | number)[]
const c = tuple(raw);
// (string | number)[]The literal expression ["a", 1] appeared in the declaration of raw, not in the call to tuple. By the time tuple sees it, widening has already happened. Fix this at the declaration, with as const there, or pass the literal directly to the function.
The same applies to values returned from other function calls. Only a literal written in the argument position benefits.
The constraint gotcha: readonly versus mutable
The const modifier produces readonly types. If your constraint demands a mutable array, the inferred readonly tuple does not satisfy it. The compiler then falls back to the constraint:
function tupleMutable<const T extends unknown[]>(items: T): T {
return items;
}
const m = tupleMutable(["a", 1]);
// TypeScript 5.0: unknown[]The result is unknown[], which is worse than the loose version. All literal information is lost, and there is no error to tell you. Newer TypeScript releases have improved inference in this case, so the exact result depends on your compiler version.
The reliable fix is to declare the constraint as readonly, which is what every example in this chapter does:
function tupleReadonly<const T extends readonly unknown[]>(items: T): T {
return items;
}Use readonly in constraints whenever you apply const to an array-like parameter. This matches how as const arrays already behave elsewhere.
Readonly results and downstream functions
Because the result is readonly, it follows the assignability rules from the earlier chapter. A function that takes string[] rejects it:
function joinAll(parts: string[]): string {
return parts.join(",");
}
function joinAllReadonly(parts: readonly string[]): string {
return parts.join(",");
}
const names = tuple(["a", "b"]);
// readonly ["a", "b"]
// joinAll(names);
// error: The type 'readonly ["a", "b"]' is 'readonly' and cannot be assigned to the mutable type 'string[]'
joinAllReadonly(names); // OKThe fix is the same as before. Functions that only read their input should declare readonly parameter types. Avoid casting the result back to a mutable array. That hides the compile-time protection, and nothing enforces it at runtime anyway.
Methods and classes
The modifier is allowed on type parameters of functions, methods, and classes. Arrow functions work too, but in a .tsx file you may need a trailing comma or an extends clause so the parser does not read <const T> as a JSX tag.
class Box<const T> {
constructor(readonly value: T) {}
}
const box = new Box({ id: 1, tags: ["x", "y"] });
// Box<{ readonly id: 1; readonly tags: readonly ["x", "y"] }>It is not allowed on type aliases or interfaces. The compiler reports an error there, because those declarations do not infer anything from arguments.
const identity = <const T extends readonly unknown[]>(items: T): T => items;
const u = identity([true, "yes"]);
// readonly [true, "yes"]Choosing between the three tools
You now have three ways to keep literal types. They overlap, but each fits a different situation.
| Approach | Where you write it | Validates shape | Keeps literals | Best for |
|---|---|---|---|---|
| `value as const` | At each value | No | Yes | One-off constants |
| `as const satisfies T` | At each value | Yes | Yes | A single declared table or config |
| `const` type parameter | Once, in the function signature | Yes, through the constraint | Yes | Helpers called from many places |
A few rules of thumb follow from the table:
- If a value is declared once in a module,
as const satisfiesis the clearest option. Nothing needs to be generic. - If many call sites pass in literal data, put a
consttype parameter in adefineXhelper. Each caller then writes only the data. - If the function does not need to return or remember the literal type, you do not need
const. For example, a function that only reads its argument and returns astringgains nothing from it.
When `const` type parameters are not worth it
The modifier also has costs.
- Readonly spreads outward. Anything derived from the result inherits
readonly. If the rest of your code uses mutable arrays heavily, you will addreadonlyto many signatures. - Inference can get large. A big literal table becomes a very precise type. That is useful for deriving unions, but it makes hover output long and can slow the compiler on huge inputs.
- It is invisible to callers. Someone reading
defineRoles(["a", "b"])cannot tell that the call preserves literals without looking at the signature. A clear function name such asdefineRoleshelps. - Version requirement. It needs TypeScript 5.0 or later. Declaration files that use it cannot be consumed by older compilers, which matters if you publish a library.
Putting it together
This final example combines the pieces from the whole chapter. A helper validates a list of routes, preserves their literals, and a type is derived from the result.
type Route = { path: string; method: "GET" | "POST" };
function defineRoutes<const T extends readonly Route[]>(routes: T): T {
return routes;
}
const api = defineRoutes([
{ path: "/users", method: "GET" },
{ path: "/orders", method: "POST" },
]);
type ApiPath = (typeof api)[number]["path"];
// "/users" | "/orders"
function isApiPath(value: string): value is ApiPath {
return api.some((route) => route.path === value);
}
console.log(isApiPath("/users")); // true
console.log(isApiPath("/missing")); // falseThe runtime array and the ApiPath type come from one declaration. Adding a route to the array updates both. The type guard works because api is a readonly tuple of objects with known path properties, so some can compare against route.path directly.
Exercises
Exercise
You write function pick<const T extends string[]>(keys: T): T { return keys; } and call pick(["a", "b"]). In TypeScript 5.0 the result is string[], not a tuple of literals. Why, and how do you fix the signature?
Show answer
The const modifier infers the argument as readonly ["a", "b"]. That type is not assignable to the mutable constraint string[], so the compiler falls back to the constraint and the literal information is lost. Change the constraint to readonly string[]. Then pick(["a", "b"]) returns readonly ["a", "b"].
Exercise
Given function tuple<const T extends readonly unknown[]>(items: T): T { return items; }, what is the type of result in each case?
const raw = ["x", 2];
const r1 = tuple(["x", 2]);
const r2 = tuple(raw);
const r3 = tuple(["x", 2] as const);
Show answer
r1 is readonly ["x", 2], because the literal is written in the call and the const modifier applies. r2 is (string | number)[], because raw was widened when it was declared and the modifier only affects literals written in the argument. r3 is readonly ["x", 2], because the explicit as const already produced that type and the modifier agrees with it.
Exercise
Write a helper defineStatuses that accepts an array of strings and returns it with literal types preserved. Then derive a Status union type from the result for the list ["open", "closed", "pending"].
Show answer
function defineStatuses<const T extends readonly string[]>(items: T): T { return items; } const STATUSES = defineStatuses(["open", "closed", "pending"]); type Status = (typeof STATUSES)[number]; // "open" | "closed" | "pending"