简体   繁体   English

没有类的 Typescript 中的 Getter/Setter

[英]Getter / Setter in Typescript without Class

Here is a sampling of SO questions for Typescript getters/setters: from 2015 , Jan 2018 , Sept 2018 , among others.以下是 Typescript getter/setter 的 SO 问题示例: 从 2015 年开始2018 年1 月2018 9 月,等等。

That said, what is the recommended way for defining Typescript types for getters/setters in a vanilla JS object?也就是说,在 vanilla JS 对象中为 getter/setter 定义 Typescript 类型的推荐方法是什么? That is, I would like a plain old javascript object without the class syntax, and to understand the best practices for typing.也就是说,我想要一个没有class语法的普通旧 javascript 对象,并了解打字的最佳实践。 Here's the interface -界面是这样的——

interface Store {
   activeEvent: Date
}

A few constraints for this object -这个对象的一些限制 -

No new to instantiate没有new的实例化

No duplicates - this doesn't work没有重复 - 这不起作用

const Store: Store = {
  activeEvent: new Date(),
  get activeEvent() {
    return this.activeEvent;
  },
}

No dangling underscores.没有悬垂的下划线。 Airbnb's eslint config is yelling at this - Airbnb 的 eslint 配置对此大喊大叫 -

const Store: Store = {
  _activeEvent: {},
  get activeEvent() {
    return this._activeEvent;
  },

Ideally I would like to have default values (that is, if I drop the key, the error goes away, but on first access activeEvent is undefined).理想情况下,我希望有默认值(也就是说,如果我放下键,错误就会消失,但在第一次访问时, activeEvent是未定义的)。 I suppose I could init and return this.activeDate if it is undefined, which works, but get is actually get & set in that scenario -我想我可以初始化并返回this.activeDate如果它是未定义的,这有效,但在那种情况下get实际上是get & set -

 get activeDate() {
    if(this.activeDate){ return this.activeDate }
    const date = new Date()
    this.activeDate = date;
    return date;
  },

I would rather not generate duplicate keys with getters and setters just to have getters and setters.我宁愿不使用 getter 和 setter 生成重复的键,只是为了拥有 getter 和 setter。

Interestingly enough, the fact that the getter/setter have the same key doesn't error out, it's just when they match the private-ish variable, which makes me think I am doing something wrong.有趣的是,getter/setter 具有相同键的事实不会出错,只是当它们匹配 private-ish 变量时,这让我觉得我做错了什么。 I appreciate any insight.我很欣赏任何见解。

getter setter 错误

Wrap your object creation in a closure, and keep variables that aren't part of the interface outside the object:将您的对象创建包装在一个闭包中,并将不属于该接口的一部分的变量保留在对象之外:

function createStore() {
  let activeEvent = new Date();
  return {
    get activeEvent() {
      return activeEvent;
    },
  };
}

This avoids the name collision/infinite loop issue you're currently running into - the object you return has a .activeEvent getter, but the variable backing it lives outside the object, in the scope of the createStore function.这避免了您当前遇到的名称冲突/无限循环问题 - 您返回的对象具有.activeEvent getter,但支持它的变量位于对象之外,在createStore函数的范围内。

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

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