简体   繁体   English

减少打字稿中的吸气剂/设定剂样板

[英]Reducing getter/setter boilerplate in Typescript

In Typescript, I often find myself writing this sort of getter/setter boilerplate: 在Typescript中,我经常发现自己正在编写这种getter / setter样板:

private _length = 0;

get length(): number { return this._length; }
set length(value: number) { this._length = value; }

In C#, I know that you can write something like this: 在C#中,我知道您可以编写如下代码:

public length { get; set; }

Is there an equivalent way to simplify my Typescript code? 有简化我的Typescript代码的等效方法吗?

One way that I've found is to use decorators, which were introduced in Typescript 1.5. 我发现的一种方法是使用装饰器,它是在Typescript 1.5中引入的。 The implementation looks like this: 实现看起来像这样:

function prop(target: Object, name: string) {
  Object.defineProperty(target, name, {
    get: function() { return this["_" + name]; },
    set: function(value) { this["_" + name] = value; },
    enumerable: true,
    configurable: true
  });
}

Now, you can replace the code in the OP with this: 现在,您可以使用以下代码替换OP中的代码:

@prop length = 0;

One thing to note is that a _length property will be added to the object. 要注意的一件事是_length属性将添加到该对象。 If you don't need to access it, you're good! 如果您不需要访问它,那就太好了! If you do need to use it, and you want it to autocomplete, you can annotate the property like so: 如果确实需要使用它,并且希望它自动完成,则可以这样注释属性:

@prop length = 0; private _length = 0;

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

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