Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto getter and setter in TypeScript

I've created this (sort of auto getter and setter) for javaScript but I don't know how to implement this in typeScript

I want to make an Object Oriented version of that if that's possible.

like image 361
Morteza Tourani Avatar asked Oct 21 '25 11:10

Morteza Tourani


2 Answers

7 years later, TypeScript 4.9 now supports an upcoming ECMAScript feature called "auto accessors":

class MyClass {
  // This property 
  accessor myProperty: boolean = true
}

This does not provide access to the underlying private property, though. You can read up on how these work and why these were introduced here.

like image 192
Phil Kang Avatar answered Oct 22 '25 23:10

Phil Kang


Currently, there is no good way to do this. I think you will just need to go the boilerplate-y way:

class Foo {
    private _bar: number;
    get bar() { return this._bar }
    set bar(bar: number) { this._bar = bar}
    // ...
}

If you wanted, you could use an editor snippet to make this a bit less of a pain.

like image 22
Gaelan Avatar answered Oct 23 '25 00:10

Gaelan



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!