Skip to content

Instantly share code, notes, and snippets.

@KOBA789
Created July 20, 2017 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KOBA789/c975cd12675a794daab0ecba2aa6540b to your computer and use it in GitHub Desktop.
Save KOBA789/c975cd12675a794daab0ecba2aa6540b to your computer and use it in GitHub Desktop.
Type-safe URL Template
class PathTemplate<N extends string> {
constructor(public fragments: string[], public paramNames: N[]) {}
render(params: {[_ in N]: string}) {
const buf = [this.fragments[0]];
for (let i = 0; i < this.paramNames.length; ++i) {
buf.push(params[this.paramNames[i]]);
buf.push(this.fragments[i + 1]);
}
return buf.join('');
}
}
function path<N extends string>(strs: TemplateStringsArray, ...ns: N[]): PathTemplate<N> {
return new PathTemplate<N>([...strs], ns);
}
const template = path`/users/${'user_id'}/articles/${'article_id'}/comments/${'id'}`;
console.log(template.render({
user_id: '1',
article_id: '2',
id: '3',
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment