How do I define the [Symbol.iterator] function signature to use it with spread operator as function arguments?

Viewed 24

I have defined a Vec2 class:

class Vec2{
  x = 0
  y = 0

  // constructor and other methods

  *[Symbol.iterator](){
    yield this.x
    yield this.y
  }
  values():[number,number]{
    return [this.x,this.y]
  }
}

The goal is to use it in CanvasRenderingContext2D.moveTo which accepts (x:number, y:number), like this: ctx.moveTo(...vec). But typescript throws ts2556 error at me.

"A spread argument must either have a tuple type or be passed to a rest parameter" (TS2556)

Another approach is to use the values method defined above like this: ctx.moveTo(...vec.values()), which works fine but is quite tedious.

Is there a way to write type annotations to make the first approach work, or is it just impossible?

0 Answers
Related