I'm in the process of learning TypeScript. I have a class that is going to manage a set of blog posts. I need to make an array of posts available (with get) and accept a single post object with I then push to the posts class. but this gives an error
export interface PostInterface {
id: number;
title: string;
content: string;
}
class Data {
private _posts: PostInterface[] = [];
constructor() {
this._posts = [
{
id: 1,
title: "first post",
content: "first content",
},
];
}
public get posts(): PostInterface[]{
return this._posts
}
public set posts(singlePost: PostInterface[]) { // <---- THIS IS THE ISSUE
this._posts.push(singlePost[0]);
}
}
export default new Data();
It sort of works like that but that's not what I want singlePost
is not going to be an array but an object and leaving it like posts(singlePost: PostInterface)
throws an error
Back in my API I'm doing this
import Data, {PostInterface} from './data' // the above
const posts: PostInterface[] = request.body
Data.posts = posts
response.json({ data: Data.posts })
But when posting to this api I don't want to have to wrap my object into an array for no reason.
Is this really how it should work? can't I get
a list of posts (PostInterface[]
) and set a single post object (PostInterface
)
CodePudding user response:
Why not simply remove the setter and push directly to the posts
array?
Data.posts.push(request.body as PostInterface);
Otherwise, you could implement an addPost
method. This is a common practice when you want to prevent collection mutation outside the class
public get posts(): ReadonlyArray<PostInterface> {
return this._posts; // return an immutable version
}
public addPost(post: PostInterface): Data {
this._posts.push(post);
return this;
}