英文:
Updating tsconfig.json target target to "es2022" causes "Property 'xx' is used before its initialization.ts(2729)"
问题
我有很多Angular代码,其中我在其定义时分配一个属性,就像下面这样...
public errors$ = this.store$.select(fromApp.getErrors);
constructor(private store$: Store<MyState>
正如我们所看到的,store$是通过构造函数注入的。但是现在在将tsconfig.json的目标目标更改为"es2022"之后,我得到了错误
Property 'store$' is used before its initialization.ts(2729)
在声明时仍然可以分配这样的属性吗?
英文:
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?
答案1
得分: 1
你实际上不确定store$是否会在errors$之前填充。
一个很好的经验法则是在声明中初始化简单属性,但每当它依赖于其他内容时,应在构造函数中进行初始化。
public errors$: Observable<Foo>;
constructor(private store$: Store<MyState>) {
this.errors$ = this.store$.select(fromApp.getErrors);
}
在这里,你可以确定`store$`在`errors$`之前被填充。
英文:
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$.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论