MediumJavaScriptTypeScript

Template Literal Types — Route Builder

TypeScriptTypesStrings

TypeScript's template literal types let you describe and manipulate string shapes at compile time:

type EventName<T extends string> = `on${Capitalize<T>}`;
// EventName<'click'> = 'onClick'

type ExtractParams<T extends string> =
  T extends `${string}:${infer Param}/${infer Rest}`
    ? Param | ExtractParams<`/${Rest}`>
    : T extends `${string}:${infer Param}`
      ? Param
      : never;

type P = ExtractParams<'/users/:id/posts/:postId'>;
// P = 'id' | 'postId'

Your Task

Implement buildRoute(base, path, params):

  • Replace each :paramName segment in path with the corresponding value from params
  • Prepend base
  • Throw Error(Missing param: ${key}) if a param is missing
buildRoute('https://api.example.com', '/users/:id/posts/:postId', { id: '42', postId: '7' })
// → 'https://api.example.com/users/42/posts/7'

Sample tests

Test #1single param
Input: ["https://api.example.com","/users/:id",{"id":"42"}]
Output: "https://api.example.com/users/42"
Test #2multiple params
Input: ["https://api.example.com","/users/:id/posts/:postId",{"id":"42","postId":"7"}]
Output: "https://api.example.com/users/42/posts/7"
Test #3path with no params
Input: ["","/api/v1/health",{}]
Output: "/api/v1/health"