求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
相关产品推荐
相关产品推荐

