5

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 2

4

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;
Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

Thank you for your response; I'm actually looking to store abc as all HondaModels or ToyotaModels, of NissanModels, etc. ``` let abc = HondaModels ``` this returns an error
@RaySaudlach, for that latter, you need the union to be a union of the types of the enumerations, not their members: type modelTypes = typeof HondaModels | typeof ToytaModels

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.