TypeScript:按字符串比较两个枚举
TypeScript: compare two enums by string
我有 2 个枚举:
enum Insurer {
PREMERA = 'premera_blue_cross',
UHC = 'united_health_care'
}
enum ProductSource {
PremeraBlueCross = 'premera_blue_cross',
UnitedHealthCare = 'united_health_care'
}
我尝试检查 Insurer 数组是否包含 ProductSource:
const insurerArr: Insurer[] = [Insurer.PREMERA, Insurer.UHC]
insurerArr.includes(ProductSource.PremeraBlueCross)
但是 TS 编译器报错:
Argument of type 'ProductSource' is not assignable to parameter of type 'Insurer'.
有一种方法可以在不转换为 string
然后转换为另一个枚举的情况下进行比较吗?
您可能要考虑切换到 type
而不是 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'];
insurerArr.includes('premera_blue_cross');
我有 2 个枚举:
enum Insurer {
PREMERA = 'premera_blue_cross',
UHC = 'united_health_care'
}
enum ProductSource {
PremeraBlueCross = 'premera_blue_cross',
UnitedHealthCare = 'united_health_care'
}
我尝试检查 Insurer 数组是否包含 ProductSource:
const insurerArr: Insurer[] = [Insurer.PREMERA, Insurer.UHC]
insurerArr.includes(ProductSource.PremeraBlueCross)
但是 TS 编译器报错:
Argument of type 'ProductSource' is not assignable to parameter of type 'Insurer'.
有一种方法可以在不转换为 string
然后转换为另一个枚举的情况下进行比较吗?
您可能要考虑切换到 type
而不是 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'];
insurerArr.includes('premera_blue_cross');