- Learning TypeScript 2.x
- Remo H. Jansen
- 312字
- 2025-04-04 17:02:05
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 that contains all the static literals in the template string (<h1> and </h1> in the preceding example) is passed as the first argument.
- A REST parameter is passed as the second parameter. The REST parameter contains all the values in the template string (name and surname, in the preceding example).
The signature of a tag function looks as follows:
tag(literals: TemplateStringsArray, ...placeholders: any[]): string;
Let's implement the htmlEscape tag function:
function htmlEscape(literals: TemplateStringsArray, ...placeholders: any[]) { let result = ""; for (let i = 0; i < placeholders.length; i++) { result += literals[i]; result += placeholders[i] .replace(/&/g, "&") .replace(/"/g, """) .replace(/"/g, "'") .replace(/</g, "<") .replace(/>/g, ">"); } result += literals[literals.length - 1]; return result; }
We can then invoke the function as follows:
let html = htmlEscape `<h1>${name} ${surname}</h1>`;
The template string contains values and literals. The htmlEscape function iterates through them and ensures that the HTML code is escaped in the values to avoid possible code injection attacks.
The main benefit of using a tagged function is that it allows us to create custom template string processors.