我在其中有一个类
和一个构造函数
。构造函数得到一个值 x
作为参数,我想用
this.x = x
但是 typescript 会抛出一个错误:
TS2339: Property 'x' does not exist in type 'myClass'
有谁知道如何在不声明每个变量的情况下解决这个问题,比如 "private x: number;
"--> "this.x = x
"
最佳答案
如果你有一个构造函数参数,你可以只声明一个访问修饰符使它成为一个字段,你甚至不需要执行赋值(typescript会为你做)
class C {
constructor(public x: number) {} // can also be private or protected instead of public
m() {
this.x = 10;
}
}
new C(1).x // ok, x is declared and is 1
关于javascript - 将变量清除为 this.x = x 时,Typescript 会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57001577/