const type parameters keep literal types
Use a const type parameter with a readonly constraint to infer literal tuples from inline arrays.
You wrote a small generic helper that takes a list and returns it. At the call site you want the exact values, 'red' and 'green', so you can use them as a union later. TypeScript hands you string[] instead.
function pick<T>(values: T): T {
return values
}
const colors = pick(['red', 'green'])
const t1: number = colors // fails on purpose, to print the typeThe assignment to number cannot succeed, so the compiler prints the type of colors in its error: Type 'string[]' is not assignable to type 'number'. An array literal widens to string[] unless something tells TypeScript to keep it exact. Before 5.0, callers could preserve that tuple with as const.
Mark the parameter const
TypeScript 5.0 lets you put const in front of a type parameter. TypeScript prefers literal types for inline arguments where the constraint allows them.
function pickConst<const T>(values: T): T {
return values
}
function pickMutable<const T extends string[]>(values: T): T {
return values
}
function pickReadonly<const T extends readonly string[]>(values: T): T {
return values
}
const constColors = pickConst(['red', 'green'])
const mutableColors = pickMutable(['red', 'green'])
const readonlyColors = pickReadonly(['red', 'green'])
const t2: number = constColors
const t3: number = mutableColors
const t4: number = readonlyColors
declare const one: (typeof readonlyColors)[number]
const t5: 'blue' = oneplain.ts(6,7): error TS2322: Type 'string[]' is not assignable to type 'number'.
tuples.ts(17,7): error TS2322: Type 'readonly ["red", "green"]' is not assignable to type 'number'.
tuples.ts(18,7): error TS2322: Type '["red", "green"]' is not assignable to type 'number'.
tuples.ts(19,7): error TS2322: Type 'readonly ["red", "green"]' is not assignable to type 'number'.
tuples.ts(22,7): error TS2322: Type '"red" | "green"' is not assignable to type '"blue"'.
Type '"red"' is not assignable to type '"blue"'.The first line is the plain pick from plain.ts. The next three are t2, t3 and t4 from tuples.ts, and the last is t5. With <const T> the type is readonly ["red", "green"], and indexing it with number gives the union "red" | "green".
The constraint picks the tuple kind
Here pickMutable infers ["red", "green"], while pickReadonly infers readonly ["red", "green"]. The TypeScript 5.0 release notes describe the original behavior, where the mutable constraint fell back to string[].
For a list of names I use readonly string[]. The inline literal produces a readonly tuple, so readonlyColors[0] = 'green' fails with TS2540. The helper also accepts a list typed with as const, which a string[] constraint rejects.
The modifier applies to a literal written in the call. Pass an existing const list = ['red', 'green'] and pickConst(list) still returns string[] because TypeScript widened the array at its declaration.