最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - auto getter and setter in TypeScript - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited May 23, 2017 at 12:09 CommunityBot 11 silver badge asked Sep 22, 2015 at 16:59 Morteza TouraniMorteza Tourani 3,5465 gold badges43 silver badges48 bronze badges 1
  • 1 Check out using decorators to do something like this. – rwisch45 Commented Sep 22, 2015 at 17:27
Add a ment  | 

2 Answers 2

Reset to default 6

7 years later, TypeScript 4.9 now supports an uping 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.

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.

发布评论

评论列表(0)

  1. 暂无评论