Home > Blockchain >  How to convert an object of one class into an object of another class in typescript ReactJs?
How to convert an object of one class into an object of another class in typescript ReactJs?

Time:06-18

I have two interfaces defined like this:

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[] };
}

You can see that both the interface definitions are same except for the replies field.

Now, in a .tsx file, I'm getting an object of PostView. I want to call another function which requires Post object. Also, for the replies field, I have to sent empty object to the function.

This is how I have currently.

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

You can see that I'm assigning PostView object to a variable of type any which I don't want to do. And then I'm updating replies field to empty object and casting it to Post object.

Is there a better way to write this code?

CodePudding user response:

You could create a new post object using the spread operator:

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