A typescript template string (or template literal) is a regular JavaScript string which is enclosed within the back-tick characters (`
) seeded with multiple placeholders denoted with ${ }
. At runtime, the code replaces the placeholders with their real values.
The process of evaluating a template literal containing one or more placeholders, yielding a result is also known as string interpolation.
1. Template String Example
In this example, at runtime, the code replaces the placeholders name
and age
with the actual values of variables. It’s called variable substitution.
const name: String = 'Lokesh'; const age: number = 35; let message: string = `My name is ${ name } and my age is ${ age }`; console.log(message); //My name is Lokesh and my age is 35
2. Multi-line Template Strings
Not like with regular strings where we use plus (+
) character to concatenate multi-line strings, template strings do not need plus character.
const name: String = 'Lokesh'; const age: number = 35; let message: string = `My name is ${ name } and my age is ${ age }`; //Output My name is Lokesh and my age is 35
Please notice that multi-line template strings output the string which is formatted with new line characters.
Drop me your questions in comments section.
Happy Learning !!