Home > Software engineering >  How to loop through two object keys in typescript?
How to loop through two object keys in typescript?

Time:11-15

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.

CodePudding user response:

@T.J. Crowder has commented some sound advice. However, if you are intent on using a loop in your method, you'll need to narrow the key type for the compiler:

TS Playground link

You can do it manually:

add (v: Vector): Vector {
  const vec = new Vector();

  for (const key in vec) {
    type K = 'x' | 'y';
    vec[key as K] = this[key as K]   v[key as K];
  }

  return vec;
}

Or by using an assertion function for the remainder of the scope:

function assertType <T = unknown>(value: unknown): asserts value is T {}
add (v: Vector): Vector {
  const vec = new Vector();

  for (const key in vec) {
    assertType<'x' | 'y'>(key);
    vec[key] = this[key]   v[key];
  }

  return vec;
}

CodePudding user response:

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

  • Related