TypeScript hasOwnProperty equivalent

Inn0vative1 picture Inn0vative1 · Feb 29, 2016 · Viewed 37.3k times · Source

In JavaScript, if I want to loop through a dictionary and set properties of another dictionary, I'd use something like this:

for (let key in dict) {
  if (obj.hasOwnProperty(key)) {
    obj[key] = dict[key];
  }
}

If obj is a TypeScript object (instance of a class), is there a way to perform the same operation?

Answer

basarat picture basarat · Feb 29, 2016

If obj is a TypeScript object (instance of a class), is there a way to perform the same operation?

Your JavaScript is valid TypeScript (more). So you can use the same code as it is.

Here is an example:

class Foo{
    foo = 123
}

const dict = new Foo();
const obj = {} as Foo;

for (let key in dict) {
  if (obj.hasOwnProperty(key)) {
    obj[key] = dict[key];
  }
}

Note: I would recommend Object.keys(obj).forEach(k=> even for JavaScript, but that is not the question you are asking here.