如何通过指定每个属性及其值来实例化 TypeScript 中的对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43314791/
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
How to instantiate an object in TypeScript by specifying each property and its value?
提问by YSA
Here's a snippet in which I instantiate a new content
object in my service:
这是我content
在我的服务中实例化一个新对象的片段:
const newContent = new Content(
result.obj.name
result.obj.user.firstName,
result.obj._id,
result.obj.user._id,
);
The problem is that this way of object instantiation relies on the order of properties in my content
model. I was wondering if there's a way to do it by mapping every property to the value I want to set it to, for example:
问题是这种对象实例化方式依赖于我content
模型中的属性顺序。我想知道是否有办法通过将每个属性映射到我想要设置的值来做到这一点,例如:
const newContent = new Content(
name: result.obj.name,
user: result.obj.user.
content_id: result.obj._id,
user_id: result.obj.user._id,
);
回答by Geoff Lentsch
const newContent = <Content>({
name: result.obj.name,
user: result.obj.user.
content_id: result.obj._id,
user_id: result.obj.user._id,
});
Here you can instantiate an object and use type assertion or casting to the Content type. For more information on type assertion: https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions
在这里您可以实例化一个对象并使用类型断言或转换为内容类型。有关类型断言的更多信息:https: //www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions
回答by Nitzan Tomer
You can pass an object to the constructor which wraps all of those variables:
您可以将对象传递给包装所有这些变量的构造函数:
type ContentData = {
name: string;
user: string;
content_id: string;
user_id: string;
}
class Content {
constructor(data: ContentData) {
...
}
}
And then:
接着:
const newContent = new Content({
name: result.obj.name,
user: result.obj.user.
content_id: result.obj._id,
user_id: result.obj.user._id,
});