I am facing an issue with my dataSync service where TypeScript is referring to the returned data as type object instead of type <WebPost>
, which is causing my code to break. In the dataSync service, I receive an error when hovering over the data parameter in the resolve(data)
line.
Argument of type '{ _id: string; caption: string; comments: [string]; likes: [string]; price: number; image: string; forUser: string; likesLength: 1; commentsLength: 1; isLiked: boolean; }' is not assignable to parameter of type 'WebPost | PromiseLike<WebPost>'.
How can I resolve this issue?
Here is the method in my component:
getPostFromUrl() {
this.route.params.subscribe(params => {
const id = params['id'];
this.dataSyncService.getPostData(id).then(data => {
this.data._id = id;
this.data.caption = data.caption;
this.data.comments = data.comments;
this.data.likes = data.likes;
this.data.price = data.price;
this.data.image = data.image;
this.data.forUser = data.forUser;
this.data.isLiked = data.isLiked;
this.data.likesLength = data.likesLength;
this.isData = true;
});
});
}
Here is the dataSyncService:
getPostDataP(id): Promise<WebPost> {
return new Promise<WebPost>((resolve, reject) => {
this.authService.getPostP(id).subscribe(d => {
if (d.success) {
const data = {
_id: '',
caption: d.data.caption,
comments: d.data.comments,
likes: d.data.likes,
price: d.data.price,
image: d.data.imageUrl,
forUser: d.data.forUser,
likesLength: d.data.likes.length,
commentsLength: d.data.comments.length,
isLiked: d.data.isLiked
};
resolve(data);
} else {
reject();
}
});
});
}
Here is the definition of the WebPost type:
export interface WebPost {
_id: string;
image: string;
forUser: string;
price: number;
likes: [string];
comments: [object];
caption: string;
likesLength: number;
commentsLength: number;
likessLength: number;
isLiked: boolean;
}