Skip to content

.tip

· one of the small things

const type parameters keep literal types without as const

A function that takes an array of strings widens ["a", "b"] to string[], and the union is gone. A const type parameter keeps the literals at the call site.

function defineRoutes<const T extends readonly string[]>(routes: T) { return routes; }
const routes = defineRoutes(["/", "/blog"]); // readonly ["/", "/blog"]

It's been there since TypeScript 5.0. It does what as const did, moved into the signature, so every caller gets it without having to remember.

typescript