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.
Related videos on Youtube
Author by
Inn0vative1
Updated on February 11, 2022Comments
-
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 almost 8 yearsI 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 over 7 yearsLet'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 ofObject.keys
orthis.hasOwnProperty(k)
since the autogen javascript has no knowledge of those properties. -
Coo almost 7 yearsWhy would you recommend
Object.keys(obj).forEach(k=>
overfor()
? -
Pang almost 2 yearsLink in answer is dead - "404 | Page not found"