如何通过指定每个属性及其值来实例化TypeScript中的对象? [英] How to instantiate an object in TypeScript by specifying each property and its value?

查看:228
本文介绍了如何通过指定每个属性及其值来实例化TypeScript中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个片段,其中我在服务中实例化了一个新的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆