skip to Main Content

With TypeScript, we cannot compare two enums even if they literally have the same values:

enum Test {
  CUSTOMERS = 'CUSTOMERS',
  CASHFLOW = 'CASHFLOW',
  SUPPLIERS = 'SUPPLIERS',
  DEBTS = 'DEBTS',
}

enum Test2 {
  CUSTOMERS = 'CUSTOMERS',
  CASHFLOW = 'CASHFLOW',
}

if (Test.CUSTOMERS === Test2.CUSTOMERS) {
  // This comparison seems unintentional, as the 'Test' and 'Test2' types have no overlap.ts(2367)
}

How do you create a Test2 enum, cloning only Test.CUSTOMERS & Test.CASHFLOW so that the test doesn’t return an error ?

2

Answers


  1. You can use something like this to remove the error.

    if (Test.CUSTOMERS === Test2.CUSTOMERS as unknown) {
      // This comparison is intentional
    }
    

    By using as unknown, you are telling TypeScript that you are aware of the potential type mismatch and that this specific comparison is intentional.

    NOTE: Please use type assertions with caution, as they can suppress type safety checks, and it’s essential to be sure that the comparison is genuinely intentional.

    The other way is to use valueOf in comparison instead.

    if (Test.CUSTOMERS.valueOf() === Test2.CUSTOMERS.valueOf()) {
      
    }
    

    NOTE the error goes away as shown below in both ways.

    enter image description here

    Login or Signup to reply.
  2. This issue is one of the reasons why I would recommend staying away from enums all together.

    Typescript documents ways to avoid enums: https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums:

    Here’s an example of how to avoid enums:

    // Declare "ENUM" as const object
    const TEST = { CUSTOMERS: "CUSTOMERS", CASHFLOW : 'CASHFLOW'} as const
    // If needed EXTRACT the objects type like this
    type Test = typeof TEST[keyof typeof TEST]
    
    
    enum TEST2 {
      CUSTOMERS = "CUSTOMERS",
      CASHFLOW = 'CASHFLOW',
    }
    
    if (TEST.CUSTOMERS === TEST2.CUSTOMERS) {}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search