升级tsconfig target至es2022出现TypeError,es2021下正常求助
tsconfig target升级到es2022后类字段初始化报错排查
错误原因
当tsconfig.json的target设为es2022时,TypeScript会启用ES2022原生的类字段声明语法,类字段的初始化逻辑会被放在构造函数执行之前。你的代码中,xyz$作为类字段,在构造函数完成otherService注入前就尝试访问this.otherService,此时otherService还未被初始化,触发Cannot read properties of undefined错误。
而target为es2021及更低版本时,TypeScript会将类字段的初始化逻辑编译到构造函数内部、参数注入之后的位置,因此不会出现该问题。
解决方法
方法1:将类字段初始化移至构造函数内
调整代码结构,确保otherService注入完成后再初始化xyz$:
export class MyService { private xyz$; constructor(private readonly otherService: SettingsService) { this.xyz$ = this.otherService.getSomeValue().pipe(...); } }
方法2:强制禁用原生类字段编译
在tsconfig.json的compilerOptions中添加useDefineForClassFields: false,让TypeScript继续使用旧的类字段编译逻辑,即使target设为es2022:
{ "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "downlevelIteration": true, "experimentalDecorators": true, "moduleResolution": "node", "importHelpers": true, "target": "es2022", "module": "es2022", "resolveJsonModule": true, "useDefineForClassFields": false } }
方法3:改用getter延迟初始化
将xyz$改为getter属性,延迟初始化时机,确保第一次访问时otherService已就绪:
export class MyService { private get xyz$() { return this.otherService.getSomeValue().pipe(...); } constructor(private readonly otherService: SettingsService) {} }
内容的提问来源于stack exchange,提问作者GarfieldKlon
相关产品推荐
相关产品推荐

