Template literal types for typed route strings
Derive parameters from a literal route so TypeScript catches missing or misspelled keys at the call site.
You have a buildPath helper that fills :id style segments in a route string. A typo in a param name passes the compiler and ships a broken URL.
function buildPath(path: string, params: Record<string, string>): string {
let out = path
for (const [key, value] of Object.entries(params)) {
out = out.replace(`:${key}`, value)
}
return out
}
console.log(buildPath('/users/:id/posts/:postId', { id: '7', postid: '42' }))
// prints /users/7/posts/:postIdtsc --noEmit --strict --target es2022 loose.ts passes, and npx tsx loose.ts prints the URL above. The key postid matched nothing, so :postId stayed in the path.
Read the params out of the string
A template literal type can pattern-match a string type and capture pieces with infer. Split the path at each slash and collect the names from segments that start with :. For /users/:id/posts/:postId, PathParamNames produces 'id' | 'postId'.
type ParamName<Segment extends string> = Segment extends `:${infer Name}` ? Name : never
type PathParamNames<Path extends string> =
Path extends `${infer Segment}/${infer Rest}`
? ParamName<Segment> | PathParamNames<Rest>
: ParamName<Path>
type PathParams<Path extends string> = Record<PathParamNames<Path>, string>
function buildPath<T extends string>(path: T, params: PathParams<T>): string {
const values = new Map(Object.entries<string>(params))
return path
.split('/')
.map((segment) => {
if (!segment.startsWith(':')) return segment
const name = segment.slice(1)
const value = values.get(name)
if (value === undefined) throw new Error(`Missing route parameter: ${name}`)
return encodeURIComponent(value)
})
.join('/')
}
console.log(buildPath('/users/:id/posts/:postId', { id: '7', postId: '42' }))
// prints /users/7/posts/42This prints /users/7/posts/42. Matching whole segments keeps :id from replacing the start of :id2 and fills repeated parameters. encodeURIComponent keeps a value such as a/b within one path segment.
Call it wrong
I appended two bad calls to the same file and ran tsc again.
buildPath('/users/:id/posts/:postId', { id: '7', postid: '42' })
// error TS2561: Object literal may only specify known properties, but 'postid' does not exist in type 'PathParams<"/users/:id/posts/:postId">'. Did you mean to write 'postId'?
buildPath('/users/:id/posts/:postId', { id: '7' })
// error TS2345: Argument of type '{ id: string; }' is not assignable to parameter of type 'PathParams<"/users/:id/posts/:postId">'.Both calls fail at compile time. The first suggests postId. The second reports that postId is required.
Use this helper with a single literal pathname, whole :name segments and values such as IDs or slugs. With a plain string, TypeScript cannot infer the parameter names. For a static path the parameter type has no required keys, so pass an empty object.