javascript - 在 setter 中使用带有类型保护的 getter 和 setter

标签 javascript typescript getter-setter

我想在我的类中添加一个 getter 和 setter。然而,setter 应该接收一个 querySelector,但 getter 返回一个新类型 pageSections

我的问题是 getter 和 setter 必须具有相同的参数/返回值,但我想将类型保护放在 setter 中。 pageSections 在类型定义文件中定义并且工作正常。

// in the code …
this.parent(this.closest('page-sections'))

// in the class
PageSection {
  private _parent: pageSections = undefined

  /**
   * @method setter parent
   * @description set the parent property
   */
  set parent (parent: pageSections) {
    if (this._parent === parent) return
    if (typeof parent.current === undefined) return // this validates it being a pageSections for now
    this._parent = parent
  }

  /**
   * @method getter parent
   * @description get the parent property
   */
  get parent (): pageSections {
    return this._parent
  }
}  

我错过了什么?这应该如何完成?

最佳答案

你不能这样做,为什么可以这样做?

你可以:

  • 创建另一个方法 (setParent(q:querySelector))
  • 创建一个转换器,详细说明 querySelector 并返回要使用“setparent”设置的 pageSections

您可以在这里找到issue关于它(从 2015 年开始仍在讨论)。

关于javascript - 在 setter 中使用带有类型保护的 getter 和 setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51065681/

相关文章:

javascript - Android 浏览器在鼠标按下 1 秒后长时间按住禁用/鼠标松开

javascript - Winforms 相当于 javascript setTimeout

javascript - 如何在 Node 中解析 HTTP 状态码?

typescript - NextJS、Storybook、SVG 和绝对导入路径

c# - VS2005 C# : is there a special visual-studio way to create properties or can the the code just be typed out?

javascript - AngularJS 指令 : compile template and watch scope

typescript - 如何在使用 `ts` 的 `d.ts` 文件中导入 `declare namespace` 模块?

javascript - TypeScript 奇怪的值

C# 优化新对象的创建(太多,丑陋的代码)

JavaBeans:如何拥有私有(private)数据?