I have a specific route set up where I need to retrieve all posts (similar to those on Twitter) from the database. To organize the likes and images for each post, I've created separate tables called "post_likes" and "post_images".
Once I fetch the posts, I aim to aggregate the likes for each post before returning them to the client.
However, when iterating through an array and using conn.query
each time, I encounter these two errors:
error TS7034: Variable 'conn' implicitly has type 'any' in some locations where its type cannot be determined.
error TS7005: Variable 'conn' implicitly has an 'any' type.
I wonder why TypeScript struggles to infer the type of conn within a map or forEach loop?
router.get("/get/:token", async (req: Request, res: Response) => {
/**
* Gets all Post from you and your friends
*/
...
let conn; // ERROR <-- Variable 'conn' implicitly has type 'any' in some locations where its type cannot be determined.
try {
conn = await pool.getConnection();
...
/* get all posts */
const queryGetPostsResult = await conn.query(queryGetPosts);
const getPosts: Array<Post> = [...queryGetPostsResult];
/* add images and likes to each post */
let clientPosts: Array<ClientPost> = await Promise.all(getPosts.map(async (post: Post) => {
/* FIXME get the likes */
const queryGetLikes: string = `SELECT user_id FROM post_likes WHERE post_id=?`
const queryGetLikesResult = await conn.query(queryGetLikes, [post.id]); // ERROR <-- Variable 'conn' implicitly has an 'any' type.
const likes: Array<number> = queryGetLikesResult.map((x: { user_id: number }) => x.user_id);
/* TODO get the images */
const images: Array<string> = [];
const clientPost: ClientPost = {
id: post.id,
writtenBy: post.written_by,
content: post.content,
writtenAt: post.written_at,
images,
likes,
};
return clientPost;
}));
return res.send(clientPosts);
} catch(err: unknown) {
throw console.log(colors.red(`/api/post/get/:token => ${err}`));
} finally {
if (conn) return conn.release();
}
});