const type parameter
A type parameter marked const, such as <const T>, which makes the compiler infer the exact literal types of arguments, as if the caller wrote as const.
In more detail
Added in TypeScript 5.0, it lets defineRoutes([...]) keep "/health" and "GET" instead of widening them to string. The inferred arrays become readonly tuples, so the constraint should also say readonly.
Example
function defineRoutes<const T extends readonly RouteSpec[]>(routes: T): TRelated terms
- as const — The TypeScript suffix as const, which tells the compiler to treat an object's values as fixed literal values rather than general types.
- literal type — A type that allows exactly one value, such as the string "GET", the number 404 or true.
- type widening — The compiler giving a value a broader type than its exact value, such as string instead of "production", because it might change later.
- generics — Types that take other types as parameters, so one definition works for many kinds of value.
Taught in
- Verify Your Environment: Running tsc And Bun TypeScript — Production TypeScript
- Default Generic Arguments And Multi-Type Parameters — Production TypeScript
- Const Type Parameters: Retaining Literal Types In Functions — Production TypeScript