Updating tsconfig.json target target to "es2022" causes "Property 'xx' is used before its initialization.ts(2729)"
Asked Answered
D

2

3

I have a lot of Angular code where I assign a property at its definition like the following...

 public errors$ = this.store$.select(fromApp.getErrors);

 constructor(private store$: Store<MyState>

As we can see store$ is injected via the constructor. But now after changing tsconfig.json target target to "es2022" I get the error

Property 'store$' is used before its initialization.ts(2729)

Are we still able to assign such properties at the declaration?

Dayna answered 22/6, 2023 at 7:41 Comment(0)
N
3

You actually don't know for sure if store$ will be filled before or after errors$.
A good rule of thumb is to initialize simple properties within the declaration, but whenever it depends on something else, do it in the constructor.

public errors$: Observable<Foo>;

constructor(private store$: Store<MyState>) {
   this.errors$ = this.store$.select(fromApp.getErrors);
}

here, you're certain store$ is filled before errors$.

Nellenelli answered 22/6, 2023 at 8:4 Comment(1)
Ok I use to always do that, but saw a lot of others always assigning at the declaration. I suppose I ca go back to the other wayDayna
C
0

you can change the way property is being initialised in ES2022. Just add "useDefineForClassFields": false in your tsconfig.json and everything will work as previously.

Long story short, till ES2021 properties was always initialised after constructor. So your code worked, but in ES2022 they change it and now properties are initialised before constructor which leads for your case that when public errors$ = this.store$.select(fromApp.getErrors); is being executed no one even god xD don't know what is your this.store$ variable.

For our fortune they provide us a switcher which changing the way it works.

For more information you can visit https://angular.schule/blog/2022-11-use-define-for-class-fields

Candleberry answered 26/9, 2024 at 20:13 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.