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

解决TypeScript ESLint strict-boolean-expressions规则报错问题

问题分析

报错源于两个核心问题:

  1. 类型定义偏差:IngredientsType的groups被定义为固定长度为1的元组['vegan' | 'vegetarian'] | undefined,但实际场景中groups应为可包含多个值的数组,这种定义导致TypeScript对数组方法的推断异常,ESLint判定条件中存在潜在any值。
  2. ESLint规则约束:@typescript-eslint/strict-boolean-expressions规则禁止条件中使用隐式布尔转换,直接用!includes(...)这类取反写法会触发报错,要求显式比较或类型转换。

解决方案

1. 修正类型定义

将IngredientsType中的groups改为动态数组类型,匹配实际数据结构:

interface IngredientsType {
  name: string
  // 替换固定元组为动态数组
  groups: ('vegan' | 'vegetarian')[] | undefined
  options: [
    {
      name: string
      quality: 'high' | 'medium' | 'low'
      price: number
      per_amount: 'kilogram' | 'litre'
    }
  ]
}

2. 调整条件语句写法

由于前面已通过if (ingredientFull === undefined || ingredientFull.groups === undefined)过滤了groups为undefined的情况,可安全移除可选链,并显式比较includes结果:

第56-57行修改:

if (
  ingredientFull.groups.includes('vegan') === false ||
  ingredientFull.groups.includes('vegetarian') === true
) {
  vegan = false
}

第74行修改:

if (ingredientFull.groups.includes('vegetarian') === false) {
  vegetarian = false
}

可选优化:简化过滤逻辑

用every替换forEach,让代码更简洁且符合规则:

// 素食过滤函数示例
filterFn = (meal: MealType) => {
  return meal.ingredients.every(ingredient => {
    const ingredientFull = ingredients.find(i => i.name === ingredient.name)
    return ingredientFull?.groups?.includes('vegetarian') ?? false
  })
}

额外说明

IDE未提示错误大概率是ESLint配置未在IDE中生效,可检查IDE的ESLint插件是否启用,以及项目根目录的.eslintrc是否正确配置@typescript-eslint/strict-boolean-expressions规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 17:11:16