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

升级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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:57:58