如何通过指定每个属性及其值来实例化TypeScript中的对象? [英] How to instantiate an object in TypeScript by specifying each property and its value?
问题描述
这是一个片段,其中我在服务中实例化了一个新的content
对象:
Here's a snippet in which I instantiate a new content
object in my service:
const newContent = new Content(
result.obj.name
result.obj.user.firstName,
result.obj._id,
result.obj.user._id,
);
问题在于对象实例化的这种方式依赖于我的content
模型中属性的顺序.我想知道是否有一种方法可以通过将每个属性映射到我想为其设置的值来实现,例如:
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:
const newContent = new Content(
name: result.obj.name,
user: result.obj.user.
content_id: result.obj._id,
user_id: result.obj.user._id,
);
推荐答案
const newContent = <Content>({
name: result.obj.name,
user: result.obj.user.
content_id: result.obj._id,
user_id: result.obj.user._id,
});
在这里您可以实例化对象并使用类型断言或强制转换为Content类型. 有关类型断言的更多信息: https://www.typescriptlang. org/docs/handbook/basic-types.html#type-assertions
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
这篇关于如何通过指定每个属性及其值来实例化TypeScript中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!