Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript throws error when declearing a variable as this.x = x

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"

like image 584
René Avatar asked Dec 15 '25 17:12

René


1 Answers

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
like image 96
Titian Cernicova-Dragomir Avatar answered Dec 17 '25 10:12

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!