Typescript create type from multiple Unions for Record Key

Say I have:

type Eggs = "Scrambled" | "Fried" | "Poached"
type Drink = "Coffee" | "Orange Juice" | "Milk"
type Meat = "Bacon" | "Sausage" | "Steak"

I want to create a Record type that uses each combination of the values of those types as a key. So

combinedType = Combined<Eggs, Drink, Meat> // How do I write Combined?
myRecord = Record<combinedType, number>

myObj: myRecord = {
"Scrambled_Coffee_Bacon": 2.3,
"Scrambled_Coffee_Sausage": 4.1,
.....

}

Ultimately the purpose is to ensure that myObj has a key/value pair for each combination of my types.

>Solution :

You can utilize Template Literal Types:

type CombinedType = `${Eggs}_${Drink}_${Meat}`;

Leave a Reply