TypeScript: compare two enums by string

I have 2 enums:

enum Insurer {
  PREMERA = 'premera_blue_cross',
  UHC = 'united_health_care'

enum ProductSource {
  PremeraBlueCross = 'premera_blue_cross',
  UnitedHealthCare = 'united_health_care'

I try check if array of Insurer includes ProductSource:

const insurerArr: Insurer[] = [Insurer.PREMERA, Insurer.UHC]

But got an error from the TS compiler:

Argument of type 'ProductSource' is not assignable to parameter of type 'Insurer'.

There is a way to compare without do a casting to string and then to the other enum?

>Solution :

You may want to consider to switch to type instead of enum:

type Insurer = 'premera_blue_cross' | 'united_health_care';
type ProductSource = 'premera_blue_cross' | 'united_health_care';
const insurerArr: Insurer[] = ['premera_blue_cross', 'united_health_care'];

Leave a Reply