TypeScript hasOwnProperty equivalent

60.8k Views Asked by At

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?

4

There are 4 best solutions below

3
On BEST ANSWER

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.

0
On
0
On

You could probably just use ECMAScript 6's Object.assign(obj, dict);.

TypeScript's spread operator comes to mind, but I don't think it's applicable because that's for creating a new object, you want to overwrite properties in an existing class.

Things to be aware of is it is only a shallow copy, and it will invoke setters in the target class if they exist.

0
On

I found fp-ts has function worked best for my use case:

const role = 'mother' as string
const rolesConst = {
  mother: 'mother',
  father: 'father'
} as const
if (has(role, rolesConst)) {
  // role's type is 'mother' | 'father'
}

https://gcanti.github.io/fp-ts/modules/ReadonlyRecord.ts.html#has