Tag functions and tagged templates

In TypeScript, we can use template strings such as the following:

let name = "remo"; 
let surname = "jansen"; 
let html = `<h1>${name} ${surname}</h1>`; 

We can use a template string to create a special kind of function known as a tag function.

We can use a tag function to extend or modify the standard behavior of template strings. When we apply a tag function to a template string, the template string becomes a tagged template.

We are going to implement a tag function named htmlEscape. To use a tag function, we must use the name of the function followed by a template string:

    
    let html = htmlEscape `<h1>${name} ${surname}</h1>`;
  

A tag template must return a string and take the following arguments:

  • A TemplateStringsArray ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.