TypeScript用as const对象替代枚举时类型不匹配如何修复?
问题根因
你为getIcon函数入参标注的typeof types是整个types常量对象的类型,而你实际传入的是types对象的属性值,二者类型自然不匹配。你需要的是types对象所有属性值组成的联合类型。
修复方案
使用TypeScript索引访问类型,提取types对象所有值的联合类型作为入参类型即可,有两种常用写法:
写法1:直接内联类型
直接在入参位置标注类型为typeof types[keyof typeof types]:
export default function App() { const types = { SUCCESS: "SUCCESS", WARNING: "WARNING", ERROR: "ERROR" } as const; // 仅修改入参类型即可解决报错 const getIcon = (type: typeof types[keyof typeof types]): string => { if (type === types.WARNING) { return "A"; } if (type === types.ERROR) { return "B"; } return "C"; }; const myIcon = getIcon(types.WARNING); return ( <div className="App"> <h1>{myIcon}</h1> </div> ); }
写法2:抽离公共类型方便复用
如果这个枚举值类型需要在多个地方使用,可以提前抽离为独立类型:
export default function App() { const types = { SUCCESS: "SUCCESS", WARNING: "WARNING", ERROR: "ERROR" } as const; // 抽离独立的枚举值类型,后续其他逻辑也可复用 type MessageType = typeof types[keyof typeof types] const getIcon = (type: MessageType): string => { if (type === types.WARNING) { return "A"; } if (type === types.ERROR) { return "B"; } return "C"; }; const myIcon = getIcon(types.WARNING); return ( <div className="App"> <h1>{myIcon}</h1> </div> ); }
内容的提问来源于stack exchange,提问作者Magofoco
相关产品推荐
相关产品推荐

