繁体   English   中英

如何在 typescript ReactJs 中将一个类的对象转换为另一个类的对象?

[英]How to convert an object of one class into an object of another class in typescript ReactJs?

我有两个这样定义的接口:

export interface PostView{
    postName: string;
    postTime: Time;
    message: string | null;
    replies: { [P in AccountType]?: Reply[][] };
}

export interface Post{
    postName: string;
    postTime: Time;
    message: string | null;
    replies: { [P in AccountType]?: Reply[] };
}

您可以看到除了replies字段之外,两个interface定义都是相同的。

现在,在一个.tsx文件中,我得到一个PostView对象。 我想调用另一个需要Post对象的函数。 此外,对于replies字段,我必须向函数发送空对象。

这就是我目前的情况。

  const postViewObject: any = props.myPostView;
  postViewObject.replies= {};
  const request: Post = postViewObject;
  functionToBeCalled(request);

您可以看到我正在将PostView对象分配给我不想做的any类型的变量。 然后我将replies字段更新为空对象并将其转换为Post对象。

有没有更好的方法来编写这段代码?

您可以使用扩展运算符创建一个新的帖子对象:

const request: Post = {
    ...props.myPostView,
    replies: {}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM