类型“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
相关产品推荐
相关产品推荐

