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

huangapple go评论66阅读模式
英文:

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&lt;MyState&gt;

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

Property &#39;store$&#39; 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&lt;Foo&gt;;

constructor(private store$: Store&lt;MyState&gt;) {
   this.errors$ = this.store$.select(fromApp.getErrors);
}

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

huangapple
  • 本文由 发表于 2023年6月22日 15:41:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529602.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定