How to loop through two object keys in typescript?

0

Issue

I made a Vector class but I have some problem with the syntax.

This is my code:

export class Vector {
  x: number;
  y: number;

  constructor(x = 0, y = 0) {
    this.x = x;
    this.y = y;
  }

  add(v: Vector) {
    var x: number, y: number;

    for (var component in this) {
      component == "x"
        ? (x = this[component] + v[component])
        : (y = this[component] + v[component]);
    }

    return new Vector(x, y);
  }
}

Here is the syntax problem I have:

enter image description here

As you see "x" and "y" in line "return new Vector(x,y)" say "Variable ‘x’ is used before being assigned"… And for the "v[component]" says "Type ‘Extract<keyof this, string>’ cannot be used to index type ‘Vector’."

I don’t know what I have done wrong, the code works but I want to write it correctly.

Solution

Personally this is the way I would do it.

  add(v: Vector): vector {
    const res = new Vector();

    Object.keys(this).forEach(component => {
      res[component] = this[component] + v[component];
    });

    return res;
  }

I threw together a quick sandbox example here

Answered By – BigBadBenny

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More