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:
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:
Of course this is a contrived example, let us create a more realistic one for example to specify a valid padding value: