TypeScript hasOwnProperty equivalent

44,279

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.

Share:
44,279

Related videos on Youtube

Inn0vative1
Author by

Inn0vative1

Updated on February 11, 2022

Comments

  • Inn0vative1
    Inn0vative1 about 2 years

    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?

  • dSebastien
    dSebastien almost 8 years
    I have a side question about this; in your case you initialize the foo property, which ensures that it is present in the generated js code; although if the property is not defined, then it's not part of the generated code at all. Do you know why that is? This surprised me a bit when I tried using hasOwnProperty on some instance and got false back although I expected it to be present but undefined.
  • loretoparisi
    loretoparisi over 7 years
    Let's consider that undefined properties i.e. all properties that are defined in the typescript class A { prop1:string, prop2:number} will not be enumerated by any of Object.keys or this.hasOwnProperty(k) since the autogen javascript has no knowledge of those properties.
  • Coo
    Coo almost 7 years
    Why would you recommend Object.keys(obj).forEach(k=> over for() ?
  • Pang
    Pang almost 2 years
    Link in answer is dead - "404 | Page not found"