I got a class and a constructor in it. The constructor got a value x as a parameter and I want to declare a variable for the class with
this.x = x
but typescript throws an error:
TS2339: Property 'x' does not exist in type 'myClass'
Does anyone know how to solve this problem without declaring every single variable extra like "private x: number;" --> "this.x = x"
If you have a constructor parameter, you can just declare an access modifier to make it a field, You don't even need to perform the assignment (typescript will do it for you)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With