Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

241
Views
Llamar a conn.query en un bucle provoca: La variable 'conn' implícitamente tiene un tipo 'cualquiera'

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(); } });
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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(); } });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!