TypeScript中使用枚举作为键的类型错误及优化方案咨询
解决方案
方案1:类型断言快速修复
直接将serviceName断言为枚举的合法键类型,搭配存在性检查即可消除报错:
const barKey = serviceName as keyof typeof DialogBar; if (DialogBar[barKey]) { setDialogBarOpen(DialogBar[barKey]); }
方案2:类型守卫做严谨校验
编写类型守卫函数,让TypeScript自动收窄serviceName的类型,无需手动断言:
function isDialogBarKey(key: string): key is keyof typeof DialogBar { return Object.keys(DialogBar).includes(key); } if (isDialogBarKey(serviceName)) { setDialogBarOpen(DialogBar[serviceName]); }
方案3:改用常量对象替代枚举
如果不需要枚举的特定特性,用常量对象+类型定义的方式更灵活:
const DialogBar = { None: 'none', Jira: 'jira', Kisi: 'kisi', Greenhouse: 'greenhouse', } as const; type DialogBar = typeof DialogBar[keyof typeof DialogBar]; // 使用时直接通过in操作符判断合法性 if (serviceName in DialogBar) { setDialogBarOpen(DialogBar[serviceName as keyof typeof DialogBar]); }
内容的提问来源于stack exchange,提问作者Alwaysblue
相关产品推荐
相关产品推荐

