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

类型“string”无法分配给类型“Bills”的参数问题求解

解决TypeScript枚举类型不匹配错误:Argument of type 'string' is not assignable to parameter of type 'Bills'

错误原因

你定义的bill变量被TypeScript自动推断为string类型,而updatedBills是Bills枚举类型的数组,includes方法仅接受Bills类型的参数,因此出现类型不兼容的报错。

解决方案

方案1:明确指定bill的类型为Bills

直接将bill的类型声明为枚举类型,让TypeScript识别它属于Bills的成员:

enum Bills {
  BILL1 = 'BILL1',
  BILL2 = 'BILL2',
  BILL3 = 'BILL3',
}
const bill: Bills = 'BILL1'; // 显式指定类型为Bills
const updatedBills = [Bills.BILL1, Bills.BILL2, Bills.BILL3];
const isBillUpdated = updatedBills.includes(bill);

方案2:使用类型断言转换类型

如果无法提前确定bill的类型,可通过类型断言将string强制转换为Bills类型:

enum Bills {
  BILL1 = 'BILL1',
  BILL2 = 'BILL2',
  BILL3 = 'BILL3',
}
const bill = 'BILL1';
const updatedBills = [Bills.BILL1, Bills.BILL2, Bills.BILL3];
const isBillUpdated = updatedBills.includes(bill as Bills); // 类型断言转换

方案3:先校验字符串有效性再转换

若不确定bill的字符串是否属于枚举的有效成员,建议先做校验避免类型风险:

enum Bills {
  BILL1 = 'BILL1',
  BILL2 = 'BILL2',
  BILL3 = 'BILL3',
}
const bill = 'BILL1';
const updatedBills = [Bills.BILL1, Bills.BILL2, Bills.BILL3];

// 校验字符串是否为枚举的有效成员
if (Object.values(Bills).includes(bill as Bills)) {
  const isBillUpdated = updatedBills.includes(bill as Bills);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:32:41