Search code examples
javascriptobjecttypescripttypescript1.8

TypeScript hasOwnProperty equivalent


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?


Solution

  • 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.