Template Strings
Syntactically these are strings that use backticks ( i.e. ` ) instead of single (') or double (") quotes. The motivation of Template Strings is three fold:
String Interpolation
Multiline Strings
Tagged Templates
String Interpolation
Another common use case is when you want to generate some string out of some static strings + some variables. For this you would need some templating logic and this is where template strings get their name from. Here's how you would potentially generate an html string previously:
Now with template strings you can just do:
Note that any placeholder inside the interpolation (${
and }
) is treated as a JavaScript expression and evaluated as such e.g. you can do fancy math.
Multiline Strings
Ever wanted to put a newline in a JavaScript string? Perhaps you wanted to embed some lyrics? You would have needed to escape the literal newline using our favorite escape character \
, and then put a new line into the string manually \n
at the next line. This is shown below:
With TypeScript you can just use a template string:
Tagged Templates
You can place a function (called a tag
) before the template string and it gets the opportunity to pre process the template string literals plus the values of all the placeholder expressions and return a result. A few notes:
All the static literals are passed in as an array for the first argument.
All the values of the placeholders expressions are passed in as the remaining arguments. Most commonly you would just use rest parameters to convert these into an array as well.
Here is an example where we have a tag function (named htmlEscape
) that escapes the html from all the placeholders:
Note: You can annotate
placeholders
to be any[]
. Whatever you annotate it as, TypeScript will type check to make sure the placeholders used to call the tag match the annotation. For example if you expect to deal withstring
ornumber
s you can annotate...placeholders:(string | number)[]
Generated JS
For pre ES6 compile targets the code is fairly simple. Multiline strings become escaped strings. String interpolation becomes string concatenation. Tagged Templates become function calls.
Summary
Multiline strings and string interpolation are just great things to have in any language. It's great that you can now use them in your JavaScript (thanks TypeScript!). Tagged templates allow you to create powerful string utilities.
Last updated