Typescript equivalent hasOwnProperty

In javascript, if I want to scroll through a dictionary and set the properties of another dictionary, I would use something like this:

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

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

+10
javascript object typescript
source share
2 answers

If obj is a Typescript object (class instance), is there a way to do the same operation?

Your JavaScript is valid Typescript ( more ). This way you can use the same code as it.

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 ask here.

+19
source share

Perhaps you could just use ECMAScript 2015 Object.assign(obj, dict);

The Typescript distribution operator comes to mind, but I don’t think it is applicable because to create a new object you want to overwrite the properties in an existing class.

Keep in mind that this is only a shallow copy, and it will call setters in the target class, if they exist.

0
source share

All Articles