如何通过指定每个 属性 及其值来实例化 TypeScript 中的对象?

How to instantiate an object in TypeScript by specifying each property and its value?

这是我在服务中实例化新 content 对象的片段:

const newContent = new Content(
     result.obj.name
     result.obj.user.firstName,
     result.obj._id,
     result.obj.user._id,
);

问题在于这种对象实例化方式依赖于我的 content 模型中属性的顺序。我想知道是否有办法通过将每个 属性 映射到我想要设置的值来实现,例如:

 const newContent = new Content(
     name: result.obj.name,
     user: result.obj.user.
     content_id: result.obj._id,
     user_id: result.obj.user._id,
 );

您可以将对象传递给包装所有这些变量的构造函数:

type ContentData = {
    name: string;
    user: string;
    content_id: string;
    user_id: string;
}

class Content {
    constructor(data: ContentData) {
        ...
    }
}

然后:

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,
 });

在这里您可以实例化一个对象并使用类型断言或强制转换为内容类型。 有关类型断言的更多信息:https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions