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
You can use something like this to remove the error.
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.NOTE the error goes away as shown below in both ways.
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: