Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can utilize Template Literal Types:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading