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

求ESLint规则:检测useDefineForClassFields开启时类属性初始化错误

问题

开启useDefineForClassFields:true且编译目标设为es2022时,以下代码运行时会抛出Cannot read properties of undefined (reading 'array')错误,但TypeScript仅在编译目标设为EsNext时才会提前提示错误。请问有没有对应的ESLint规则能检测这个问题?

class Bar {
    array = new Array();
}

class Foo {
    foo = this.bar.array; // 此处bar未初始化就被使用

    constructor(private bar: Bar) {}
}

console.log(new Foo(new Bar()))
答案

有对应的ESLint规则可以检测该问题:

  • @typescript-eslint/no-use-before-define:通过配置该规则,可以捕获类字段中对未初始化属性的引用。建议在规则配置中关闭对函数、类等无关项的检测,聚焦于属性的提前使用问题。
  • @typescript-eslint/no-unsafe-member-access:可辅助检测这类不安全的成员访问操作,进一步提前发现潜在问题。

示例ESLint配置片段:

module.exports = {
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  rules: {
    '@typescript-eslint/no-use-before-define': [
      'error',
      {
        functions: false,
        classes: false,
        variables: false,
        ignoreTypeReferences: true
      }
    ],
    '@typescript-eslint/no-unsafe-member-access': 'error'
  }
};

本质原因:当useDefineForClassFields:true且编译目标为ES2022时,类字段的初始化顺序早于构造函数中私有参数属性的赋值,导致this.bar在foo初始化时仍为undefined,最终引发运行时错误。上述ESLint规则可在编码阶段提前识别这类问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:25:42