You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 13:36:03