Search code examples
javascripttypescriptgetter-setter

Using getter & setters with type guard in setter


I would like to add a getter and setter to my class. However the setter is supposed to receive a querySelector but the getter returns a new type pageSections.

My issue is that the getter and setter must have the same argument/return value, but I want to put the type guard in the setter. pageSections is defined in a type definition file and works fine.

// 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
  }
}  

What am I missing? How should this be done?


Solution

  • You cannot do that and why should it be possible?

    You can:

    • create another method (setParent(q:querySelector))
    • create a converter that elaborates the querySelector and returns a pageSections to set using "set parent"

    You can find here an issue about it (still discussed from 2015).