TypeScript泛型组件接收多枚举参数时类型不可比较报错如何解决
错误原因
你定义的无约束泛型T允许接收任意类型的入参,TypeScript无法确认T和AccountState/PaymentState枚举值的类型兼容性,因此会抛出两者不可比较的报错。同时你的代码还缺少对PaymentState.Pending枚举值的处理,会存在变量未赋值的隐患。
解决方案
如果你的组件仅需要支持这两种枚举,最简洁的方案是直接使用联合类型定义state属性,不需要引入泛型:
enum AccountState { Active = 'Active', Deactivated = 'Deactivated' } enum PaymentState { Paid = 'Paid', Unpaid = 'Unpaid', Pending = 'Pending' } const Indicator = (props: { state: AccountState | PaymentState }) => { let indicatorColor: string; switch (props.state) { case AccountState.Active: case PaymentState.Paid: indicatorColor = 'green'; break; case AccountState.Deactivated: case PaymentState.Unpaid: indicatorColor = 'red'; break; // 补全Pending状态的处理 case PaymentState.Pending: indicatorColor = 'orange'; break; } return ( <span style={{ width: '10px', height: '10px', borderRadius: '50%', backgroundColor: indicatorColor, }} /> ); };
如果你后续需要扩展更多支持的枚举类型,可以用泛型+类型约束的写法:
// 定义所有支持的枚举类型联合 type SupportedState = AccountState | PaymentState; const Indicator = <T extends SupportedState>(props: { state: T }) => { // 内部switch逻辑和上面完全一致,不会再触发类型报错 // ...其余代码不变 }
两种写法都可以正确支持以下调用:
<Indicator state={AccountState.Active} /> <Indicator state={PaymentState.Pending} />
内容的提问来源于stack exchange,提问作者LazioTibijczyk
相关产品推荐
相关产品推荐

