const type parameters — inferring the literal, not the widened type¶
Level: 301 · for anyone who has needed a literal type back from a function call
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: <const T> infers what as const would: keep(["get", "post"]) is readonly ["get", "post"] where a plain <T> gives string[]. It acts only on a literal written in the call — pass a variable and the result is string[] again.
Keywords: const type parameter
What the finished page will answer¶
- What do
plain(["get", "post"]),keep(["get", "post"])andplain(["get", "post"] as const)return when onlykeepis declared<const T>? - Why does
keep(verbs)with a variable givestring[]again? - What does
keep({ method: "get", retries: 3 })return, and why are its propertiesreadonly? - What does
<const T extends string[]>, a mutable constraint, infer in TypeScript 7, and how does that differ from the TypeScript 5.0 release notes? - Does
<const T>freeze anything at run time — what doesObject.isFrozensay about the returned array?
Examples it will need¶
-
const_type_parameters_inferred_sh.sh— the declarations tsc emits for plain, keep, keep with a variable and keep with a mutable constraint -
const_type_parameters_runtime_ts.ts— the array keep returns and Object.isFrozen of it, false, because const changed only the type
See also¶
satisfies,asand annotations — as const at the call site, the older way to get this type- Primitive and literal types — literal types, and when tsc widens them
- Arrays and tuples — readonly tuples, the type const T produces
- Generic functions — ordinary inference, which widens
- Rust: Const generics ↗ — a different idea with a similar name: Rust's const generic takes a value