TypeScriptTips

Make bugs impossible.
One TypeScript tip at a time.

I like the tricks :) – Kasia

Callable types

You can create powerful APIs by enriching a function with properties.

const person = path('/people/:id')

person({ id: 1 })
// "/people/1"

person.path('/details')({ id: 1 })
// "/people/1/details"

type Path = {
  (params: Record<string, any>): string
  path: (pattern: string) => Path
}

const path = (pattern: string): Path => {
  const paramsToPath = (params: Record<string, string>) => {
    return pattern.replace(/{{(\w+)}}/g, (_, capture) => params[capture])
  }

  paramsToPath.path = (p: string): Path => {
    return path(pattern + p)
  }

  return paramsToPath
}