Tengo una ruta como la siguiente en la que quiero obtener todas las publicaciones (como en Twitter) de la base de datos. He separado los me gusta y las imágenes de cada publicación en su propia tabla SQL llamada "post_likes" y "post_images".
Después de recuperar las publicaciones, quiero agregar los Me gusta para cada publicación y luego enviarlo de vuelta al cliente.
Pero recorrer una matriz y llamar a conn.query cada vez me da estos dos errores:
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.
¿Por qué el mecanografiado no puede determinar el tipo de conexión en un mapa o bucle forEach?
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(); } });Como TJ Crowder sugirió que el problema era la anotación de tipo faltante en let conn; pero todavía no entiendo por qué mecanografiado solo arroja un error cuando intento llamar a conn.query() dentro de un bucle. Si alguien sabe por favor que me explique esto.
También tuve que agregar if (!conn) throw "conn is undefined" para salir del bloque try & map.
Así que he editado la ruta a lo siguiente:
router.get("/get/:token", async (req: Request, res: Response) => { /** * Gets all Post from you and your friends */ ... let conn: PoolConnection | undefined; // <-- ADDED TO FIX THE ERROR!!! try { conn = await pool.getConnection(); if (!conn) throw "conn is unknown"; // <-- ADDED TO FIX THE ERROR!!! ... /* 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) => { if (!conn) throw "conn is unknown"; // <-- ADDED TO FIX THE ERROR!!! /* FIXME get the likes */ const queryGetLikes: string = `SELECT user_id FROM post_likes WHERE post_id=?` const queryGetLikesResult = await conn.query(queryGetLikes, [post.id]); 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(); } });