hegel icon indicating copy to clipboard operation
hegel copied to clipboard

Getters/setters not supported correctly

Open srg-kostyrko opened this issue 4 years ago • 2 comments

https://jsmonk.github.io/hegel/try#MYGwhgzhAECC0G8BQ1XQOYFMAu0BGAFAJSIprkBOOArhQHbQBMA3GagL5vQQ74EBuYENUwAubtgoBLOuiLjqdACaYAZjMxLEnTkmAB7OhFxhoAXmh1MAdzjFWAegfRsATwAOmbgAt91EFp4XnTUALZBFPjUuFIwMqqYFFRakNDE5gB8lmEReobG0FoWYAB0eEA

  • getter property type is inferred as () => number instead of number
  • if I try to define both getter and setter - there is an error Duplicated property definition!

Ideally, it should check that input type for setter and return type of getter are the same.

srg-kostyrko avatar Apr 13 '20 10:04 srg-kostyrko

Currently, getters/setters are not supported. But it will be. We will close the issue after adding the support. Thank you for your contribution ^_^.

JSMonk avatar Apr 14 '20 00:04 JSMonk

Hey, before you get to it, I thought I'd include some ideas here:

Some people would love to be able to specify the types of getters differently from the setters.

For example, the following is something we can normally do in plain JavaScript:

class Vec2 {
  x: number = 0
  y: number = 0
  add(other: Vec2) {}
  sub(other: Vec2) {}
  // etc
}

class Thing {
  _pos = new Vec2

  get position(): Vec2 {
    return this._pos
  }
  set position(val: [number, number] | Vec2) {
    if (Array.isArray(val)) {
      this._pos.x = val[0]
      this._pos.y = val[1]
      return
    }
    this._pos = val
  }
}

const thing = new Thing

const pos = thing.position // pos is type Vec2

console.log(pos.x, pos.y) // 0 0

thing.position = [1, 2] // this is ok, no type error

console.log(pos.x, pos.y) // 1 2

thing.position = new Vec2 // We can also do this, no type error

Here's the (looong) TypeScript issue (with many upvotes): https://github.com/microsoft/TypeScript/issues/2521

In particular, this comment has a good summary of why it is needed. Basically, there are many existing APIs, especially in the DOM, that already use these patterns in practice, but TypeScript can not type them properly.

trusktr avatar Aug 04 '20 20:08 trusktr