Javascript 打字稿 hasOwnProperty 等价物

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35691858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:07:07  来源:igfitidea点击:

Typescript hasOwnProperty equivalent

javascriptobjecttypescripttypescript1.8

提问by Inn0vative1

In javascript if I want to loop through a dictionary and set properties of another dictionary, I'd use something like this:

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

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

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

如果obj是 Typescript 对象(类的实例),有没有办法执行相同的操作?

回答by basarat

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

如果 obj 是 Typescript 对象(类的实例),有没有办法执行相同的操作?

Your JavaScript is valid TypeScript (more). So you can use the same code as it is.

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

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.

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

回答by H Dog

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

您可能只使用 ECMAScript 2015 的 Object.assign(obj, dict);

Typescript spread operatorcomes 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.

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