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

为何触发TypeScript ESLint的@typescript-eslint/no-unnecessary-condition错误?

从JavaScript切换到TypeScript时遇到@typescript-eslint/no-unnecessary-condition错误的疑问

最近从JavaScript转用TypeScript,遇到TypeScript ESLint抛出**"Unnecessary conditional, value is always truthy"**错误(对应规则@typescript-eslint/no-unnecessary-condition)。错误触发场景很奇怪,不仅出现在条件语句中,甚至像let diff = (oldIndent - newIndent) / 2这种普通赋值代码也会报错。关闭并重新打开文件后,红色波浪线依然存在,且错误出现在多个随机位置。

错误示例截图


条件语句触发错误提示

对象属性访问触发错误

赋值语句触发错误

错误出现在代码多个位置

侧边栏显示多处错误标记

项目配置文件

.prettierrc

{
  "semi": false,
  "trailingComma": "all",
  "singleQuote": true,
  "printWidth": 64,
  "tabWidth": 2,
  "useTabs": false,
  "arrowParens": "avoid",
  "quoteProps": "as-needed",
  "bracketSpacing": true,
  "proseWrap": "always",
  "endOfLine": "lf",
  "singleAttributePerLine": true,
  "prettierPath": "./node_modules/prettier"
}

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2020",
    "lib": ["es2020"],
    "outDir": "host",
    "rootDir": "make",
    "sourceMap": true,
    "strictNullChecks": true
  },
  "include": ["make"],
  "exclude": ["node_modules"]
}

.eslintrc.json

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module",
    "project": ["./tsconfig.json"]
  },
  "parser": "@typescript-eslint/parser",
  "plugins": ["@typescript-eslint"],
  "extends": [],
  "rules": {
    "curly": 2,
    "brace-style": ["error", "1tbs"],
    "@typescript-eslint/quotes": [
      "error",
      "single",
      {
        "avoidEscape": true,
        "allowTemplateLiterals": true
      }
    ],
    "@typescript-eslint/no-unnecessary-condition": {
      "allowConstantLoopConditions": true
    }
  }
}

.vscode/settings.json

{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "eslint.format.enable": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "eslint.validate": ["javascript", "typescript"],
  "eslint.nodePath": "./node_modules/eslint",
  "eslint.packageManager": "npm"
}

想问下这种错误是什么原因导致的?是我哪里配置或代码写错了,还是TypeScript ESLint的Bug?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 12:40:55