In TypeScript, template strings, also known as template literals, are a way to work with string interpolation and multiline strings more conveniently. Template strings are enclosed by backticks (`) instead of single or double quotes. Here's how you can use template strings in TypeScript:
Basic String Interpolation:
You can embed expressions inside template strings using ${}
:
typescriptlet name: string = "John";
let age: number = 25;
let message: string = `My name is ${name} and I am ${age} years old.`;
console.log(message);
This will output: My name is John and I am 25 years old.
Multiline Strings:
Template strings also allow for multiline strings without the need for concatenation or escape characters:
typescriptlet multilineString: string = `
This is a multiline string.
It spans multiple lines.
No need for escape characters or concatenation.
`;
console.log(multilineString);
Tagged Templates:
You can use tagged templates to process template literals with a function. The tag function receives the template literals and the interpolated values as separate arguments:
typescriptfunction customTag(strings: TemplateStringsArray, ...values: any[]): string {
let result: string = "";
for (let i = 0; i < strings.length; i++) {
result += strings[i];
if (i < values.length) {
result += values[i];
}
}
return result;
}
let firstName: string = "John";
let lastName: string = "Doe";
let customMessage: string = customTag`Hello, my name is ${firstName} ${lastName}.`;
console.log(customMessage);
This will output: Hello, my name is John Doe.
These are some basic examples of how to use template strings in TypeScript. They provide a concise and expressive way to work with strings and variable interpolation.