tsconfig.json目标改为es2022触发TS2729错误,能否保留原有属性声明方式?
构造函数注入属性在ES2022下的初始化问题
我有大量Angular代码采用如下方式在属性定义处直接赋值:
public errors$ = this.store$.select(fromApp.getErrors); constructor(private store$: Store<MyState>)
其中store$通过构造函数注入,但将tsconfig.json的target改为es2022后,触发TypeScript错误:
Property 'store$' is used before its initialization.ts(2729)
请问是否仍能以这种方式在声明时为属性赋值?
解决方案
可以继续使用这种声明时赋值的方式,以下是几种可行方案:
1. 修改TypeScript配置,兼容旧逻辑
在tsconfig.json的compilerOptions中添加useDefineForClassFields: false。这个配置会让TypeScript沿用ES2022之前的类字段初始化规则,允许在属性初始化器中引用构造函数注入的成员。
示例配置:
{ "compilerOptions": { "target": "es2022", "useDefineForClassFields": false, // 其他原有配置项... } }
2. 将初始化逻辑移至构造函数内
如果不想修改全局配置,可把属性初始化代码放到构造函数中,从根源避免"未初始化属性"的错误:
public errors$: Observable<Error[]>; constructor(private store$: Store<MyState>) { this.errors$ = this.store$.select(fromApp.getErrors); }
3. 提前声明属性(不推荐)
使用declare关键字提前声明注入的属性,跳过TypeScript的初始化检查,但这种方式会弱化类型校验,可能引发潜在问题,不建议大规模使用:
declare private store$: Store<MyState>; public errors$ = this.store$.select(fromApp.getErrors); constructor(store$: Store<MyState>) { this.store$ = store$; }
内容的提问来源于stack exchange,提问作者peterc
相关产品推荐
相关产品推荐

