Typescript Type of multiple enums

Viewed 983

I have multiple enums in my app

enum HondaModels {
   Accord = 'Accord',
   ...
}
enum ToytaModels {
   Camry = 'Camry',
   ...
}

In my code I check if a car model passed to me is a Honda or Toyota.

I would like to declare a type that is either HondaModels or ToyotaModels

If i try this, I get an error

 type modelTypes: HondaModels || ToyotaModels

is there a better approach to having a custom type that is one of multiple enums?

2 Answers

I would also avoid String enums. Using discriminated unions is much better because enums are strongly typed.

const HondaModels = {
  Accord: "Accord",
} as const;
type HondaModels = typeof HondaModels[keyof typeof HondaModels];

const ToyotaModels = {
  Camry: "Camry",
} as const;
type ToyotaModels = typeof ToyotaModels[keyof typeof ToyotaModels];

type modelTypes = HondaModels | ToyotaModels;

You have a syntax error

enum HondaModels {
   Accord = 'Accord',
}
enum ToytaModels {
   Camry = 'Camry',
}

type modelTypes =  typeof HondaModels | typeof ToytaModels

// Then use it like this
let abc: modelTypes = HondaModels

thanks to Aluan Haddad for the improved solution

Related