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

TypeScript中将一个枚举值赋值给另一枚举变量时报错如何解决?

报错原因

Priority和Label是两个相互独立的枚举类型,即使二者部分成员的字面量值完全相同,TypeScript类型系统也不会默认判定二者类型兼容,因此不能直接将Priority类型的priority变量赋值给Label类型的label变量。

修复方案

方案1:显式类型断言(最简实现)

当你确认else分支中priority的取值只能是Low或High,和Label对应成员的取值完全匹配时,可直接通过类型断言完成赋值:

const saveTask = ({ task, priority }: Item) => {
    const id = Date.now();
    let label: Label;
    if (priority === Priority.Medium) {
      label = Label.Med;
    } else {
      label = priority as unknown as Label;
    }
    // 后续业务逻辑不变
};

方案2:枚举映射表(最安全可维护)

提前定义Priority到Label的完整映射关系,TypeScript会自动校验映射的完整性,后续枚举成员调整时也不需要修改业务逻辑:

// 全局提前定义映射关系
const PriorityToLabel: Record<Priority, Label> = {
  [Priority.Low]: Label.Low,
  [Priority.Medium]: Label.Med,
  [Priority.High]: Label.High,
}

const saveTask = ({ task, priority }: Item) => {
    const id = Date.now();
    const label = PriorityToLabel[priority];
    // 后续业务逻辑不变
};

方案3:全分支判断(无类型hack)

通过switch分支覆盖所有Priority的取值场景,完全规避跨枚举类型直接赋值的问题:

const saveTask = ({ task, priority }: Item) => {
    const id = Date.now();
    let label: Label;
    switch(priority) {
      case Priority.Low:
        label = Label.Low;
        break;
      case Priority.Medium:
        label = Label.Med;
        break;
      case Priority.High:
        label = Label.High;
        break;
    }
    // 后续业务逻辑不变
};

内容的提问来源于stack exchange,提问作者margherita pizza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:15:02