Home > Software engineering >  Unable to do a union type involving multiple enums
Unable to do a union type involving multiple enums

Time:09-28

A simple example:

export enum EnumA {
  A = 'a',
}

export enum EnumB {
  A = 'b',
}

export class SomeEntity {
  id: string;

  type: EnumA | EnumB;
}

const foo = (seArray: SomeEntity[]) => {
  seArray.forEach((se) => {
    Object.values(EnumA).includes(se.type)
  })
}

But I get error:

TS2345: Argument of type 'EnumA | EnumB' is not assignable to parameter of type 'EnumA'.   Type 'EnumB' is not assignable to type 'EnumA'.

Looking at the ts docs I'm not sure why this is happening as se.type is the value of one of the enums of which it is union typed. Is there some special thing about enums I am missing?

CodePudding user response:

The problem is that Typescript doesn't know that you intended for Object.values(EnumA) to be an array of EnumA or EnumB; it assumes you wanted it to be an array of just EnumAs and so is trying to helpfully point out that se.type isn't there. You can fix it by explicitly specifying a wider type for Object.values(EnumA), for instance like this:

const foo = (seArray: SomeEntity[]) => {
  seArray.forEach((se) => {
    const values: (EnumA | EnumB)[]  = Object.values(EnumA);
    values.includes(se.type);
  })
}
  • Related