TypeScript Reference ยท Type Operators
TypeScript const type parameters
Reference for TypeScript const type parameters (5.0): infer literal and readonly types in generic calls without writing as const at every call site.
A const modifier on a type parameter asks the compiler to infer the argument type as if the caller had written as const. Object literals get readonly properties and literal types, and array literals become readonly tuples.
Without it, a generic function infers the widened type: ["a", "b"] becomes string[]. The modifier moves the burden of precision from every caller to the function author. It was added in TypeScript 5.0.
function keys<const T extends readonly string[]>(list: T): T { return list; } const k = keys(["a", "b"]); // readonly ["a", "b"]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
function f<const T>(x: T): T class Box<const T> { constructor(public value: T) {} } const g = <const T,>(x: T) => x;
| Part | Description |
|---|---|
const T |
Infer T from literal arguments using const-context rules. |
| Constraint | Usually readonly unknown[] or an object type; a constraint with a mutable array type makes the const inference fall back to the mutable shape. |
Applies to: function, method, class and arrow function type parameters, when the argument is an object, array or primitive literal written at the call site.
Edge cases: the modifier only affects literals written directly in the call. A variable declared earlier with a widened type is not re-inferred.
Usage notes
- Constraint must allow readonly. With
T extends string[]the readonly tuple is not assignable, so the compiler quietly falls back to the widened mutable type, as the last example shows. Usereadonly string[]. - Same as
as const, which also makes valuesreadonly. If callers need to mutate the object, take the type separately instead. - Arrow functions in
.tsxneed a trailing comma:<const T,>(x: T) => x. - Good for: route tables, configuration builders, event maps, enum-like lists, tuple-returning helpers.
- Not retroactive: only direct literals get const treatment, not values from variables or function calls.
- Version: TypeScript 5.0 or newer.