TypeScript hasOwnProperty 等效项

TypeScript hasOwnProperty equivalent

在 JavaScript 中,如果我想遍历一个字典并设置另一个字典的属性,我会使用这样的东西:

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

如果obj是一个TypeScript对象(class的实例),有没有办法执行相同的操作?

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

您的 JavaScript 是有效的 TypeScript (more)。所以你可以使用相同的代码。

这是一个例子:

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];
  }
}

注意:我会推荐 Object.keys(obj).forEach(k=> 即使 JavaScript,但这不是你在这里问的问题。

您可能只使用 ECMAScript 6's Object.assign(obj, dict);

想到

TypeScript's spread operator,但我认为它不适用,因为这是为了创建一个新对象,您想覆盖现有 class[= 中的属性20=].

需要注意的是,它只是一个浅拷贝,如果存在,它将调用目标 class 中的 setter。

我发现 fp-ts has 函数最适合我的用例:

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