Although I spend most of my time in C# land, I like to explore other programming languages to stretch my brain. Recently I was looking again at TypeScript where I noticed the concept of Template Literal Types.
How to explain Template Literal Types?
Not easy to give a good explanation. But let’s give it a try:
Template Literal Types are string literals on steroids.
Add a type variable to a Template Literal and Typescript will create a type with all the possible combinations for you. This allows you to compose types from others in a quick and easy way.
Not clear yet? Maybe I should switch to an example:
type Person = 'Jeff' | 'Maria' | |
type Greeting = `hi ${Person}!` // Template literal type |
I’ve created a string literal ‘Person’ and a Template Literal Type ‘Greeting’ using the string literal. Now only valid combinations of the two are possible:
const validGreeting: Greeting = `hi Jeff!` // | |
// ✅ Result: | |
// note that the type of `validGreeting` is the union `"hi Jeff!" | "hi Maria!` | |
const invalidGreeting: Greeting = `bye Jeff!` // | |
// ❌ Result: | |
// Type '"bye Jeff!"' is not assignable to type '"hi Jeff!" | "hi Maria!" |
Of course this is a contrived example, let us create a more realistic one for example to specify a valid padding value:
type Direction = 'left' | 'right' | 'top' | 'bottom'; | |
// ✅ Result: | |
// 'padding-left' | 'padding-right' | 'padding-top' | 'padding-bottom' | |
type CssPadding = `padding-${Direction}` |