简体   繁体   English

TypeScript 中的自动 getter 和 setter

[英]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我已经为 javaScript 创建了这个(某种自动 getter 和 setter),但我不知道如何在 typeScript 中实现它

I want to make an Object Oriented version of that if that's possible.如果可能的话,我想制作一个面向 Object 的版本。

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.如果你愿意,你可以使用一个编辑器片段来减轻它的痛苦。

7 years later, TypeScript 4.9 now supports an upcoming ECMAScript feature called "auto accessors": 7 年后,TypeScript 4.9 现在支持即将推出的 ECMAScript 功能,称为“自动访问器”:

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 .您可以在此处阅读这些内容的工作原理以及引入这些内容的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM