What is a template literal?
- TypeScript course
- Advanced
- Lesson 5/57
- 4 min
Learn to build template strings at the type level.
What is a template literal type?
A template literal type creates a type-level template string using backtick (`) and ${} syntax. Other types can be embedded inside; for example with ${string} you define a type whose suffix can be any string. This makes string literal types more flexible and lets you write types with a mandatory fixed prefix.
type Greeting = `Hello ${string}`;
const x: Greeting = "Hello world";Generic with template type
You can make a template literal type generic. The type parameter is placed inside ${T} and combines with the calling type to produce a fixed string type. This is an elegant way to define types with mandatory prefixes or suffixes. It is common to constrain T with string.
type Prefixed<T extends string> = `pre_${T}`;
type X = Prefixed<"test">; // "pre_test"Practice Write the SelamX template type
Define a template literal type named SelamX: `Merhaba ${string}`. The y variable should be of type SelamX with value "Merhaba dünya". Print y with console.log.
Starter code
// SelamX adinda template literal tur tanimla
// "Merhaba " ve string birlestirsin
// y degiskenini tanimla
// y degerini yazdirSample solution
type SelamX = `Merhaba ${string}`;
const y: SelamX = "Merhaba dünya";
console.log(y);Expected output
Merhaba dünya
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 With which syntax is a template literal type written?
- Metin<T>
- 'Metin'.concat(T)
- `Metin ${T}` Correct answer
- "Metin" + T
Explanation: A template literal type is written with backtick and ${}; not with double quotes or the plus operator.
2 Type placeholder
type Selam = `Merhaba ${____}`;
const x: Selam = "Merhaba dünya";
type Selam = `Merhaba ${string}`;
const x: Selam = "Merhaba dünya";
Explanation: A type is placed inside ${} in a template literal type; string is used to accept any string.
3 Template literal concepts
| Term | Meaning |
|---|---|
`... |
Template string syntax |
${T} |
Type placeholder |
backtick |
Template delimiter |
string |
Any string type |