Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript hasOwnProperty equivalent

Tags:

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?

like image 278
Inn0vative1 Avatar asked Feb 29 '16 04:02

Inn0vative1


People also ask

How do I use hasOwnProperty in TypeScript?

The hasOwnProperty() method returns true if the specified property is a direct property of the object — even if the value is null or undefined . The method returns false if the property is inherited, or has not been declared at all.

Should I use hasOwnProperty?

A good rule of thumb is that if you're looking to see whether an object has a property, you should use hasOwnProperty() . If you're looking to see if an object has a function that you intend to call, like checking if an object has toString() , you should use in .

What is hasOwnProperty in JavaScript?

The hasOwnProperty() method in JavaScript is used to check whether the object has the specified property as its own property. This is useful for checking if the object has inherited the property rather than being it's own. Syntax: object.hasOwnProperty( prop )

Can you use hasOwnProperty on Array?

The hasOwnProperty() method returns true if the property is directly present in the object (not in its prototype chain). If an object is an Array, then the hasOwnProperty() method can check if an index is available (not empty) in the array.


1 Answers

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.

like image 176
basarat Avatar answered Sep 23 '22 17:09

basarat