Syntax
function tuple<const T extends readonly string[]>(values: T): T { return values; }Examples
Literal Inference with const Type Parameters: working example
Run this standalone example after compiling with TypeScript 5.4+ in strict mode, targeting ES2022. Expected result: The program prints Ada 2; names retains a readonly tuple type with the two literal names.
function tuple<const T extends readonly string[]>(values: T): T {
return values;
}
const names = tuple(["Ada", "Grace"]);
const first: "Ada" = names[0];
console.log(first, names.length);- Expected result: The program prints Ada 2; names retains a readonly tuple type with the two literal names.
- The readonly constraint accommodates the narrow tuple inferred from the inline array.
- The helper returns the original array at runtime, so the type parameter itself adds no copying.
Best practices
- Use readonly constraints when callers need literal tuple inference.
- Do not describe const type parameters as runtime immutability.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook