How to perform string interpolation to TypeScript type?
String interpolation, also known as template literals are an extremely powerful tool in the JavaScript and TypeScript ecosystem.
`${`Hello`} ${`World`}` // Hello World
Can we do string interpolation when defining a type in TypeScript? The answer is yes!
Let me show you an example:
type PenguinsMembers = `${'Moose' | 'Ricky' | 'Blue'} ${`Penguin`}`
// "Moose Penguin" | "Ricky Penguin" | "Blue Penguin"
As you can see in the code example above, we created 3 potential values by using string interpolation for our type PenguinsMembers
.
How to convert array of strings to TypeScript types
Let’s say you have an array of strings, and you want to convert each name to a potential type value. How would that been done?
We can use string interpolation to make that happen!
Let’s look at a code example:
const Penguins = [
"Moose",
"Ricky",
"Blue",
] as const;
type PersonMembers = `${typeof Penguins[number]} Penguin`;
// "Moose Penguin" | "Ricky Penguin" | "Blue Penguin"
With string interpolation you can see that we’re grabbing each value from the array, and converting it into a TypeScript type.
I like to tweet about TypeScript and post helpful code snippets. Follow me there if you would like some too!