3.11 Tag functions and tagged templates

Tagged functions and tagged templates allow us to change the default behavior of string templates.

Getting Ready

All you need to be able to use tag functions and tagged templates is an installation of TypeScript version 1.5 or higher.

How to do it…

We will start by learning how to use string templates. A string template is just a string which uses some special characters to indicate that some parts of the string should be replaced with the value of some variables which are available in the string template context:

cosnt name = 'Luke';
cosnt surname = 'Skywalker';
cosnt fullname = `${name} ${fullname}`;

Now that we know how to declare a string template let’s declare a tag function:

function htmlEscape(literals: string[], ...placeholders: string[]) {
    let result = '';

    for (let i=0; i < placeholders.length; i++) {
        result += literals[i];
        result += placeholders[i]
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');

    result += literals[literals.length - 1];
    return result;

How it works…

The TypeScript compiler translated the string template into the following JavaScript code:

var fullname = name + " " + fullname;

We can use a tag function to extend or modify the default behavior of a string template. The signature of a tag template must be the following:

function htmlEscape(literals: string[], ...placeholders: string[])

The tag function takes an array of string literals from the tagged template as its first argument. For the example in this recipe the literals array contains two strings:

 "<div> I would just like to say: ",

The second parameter contains all the values of the placeholder expressions:

  "a bird in hand > two in the bush"

The tag template can then be applied to a template string which becomes a tagged template:

const say = 'a bird in hand > two in the bush';
const html = htmlEscape `<div> I would just like to say: ${say}</div>`;

After executing the tagged template, the value of the html variable should be the following:

"<div> I would just like to say: a bird in hand &gt; two in the bush</div>"

Source Code

Tag functions and tagged templates

Shiv Kushwaha