Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

247
Vistas
Calling conn.query in a loop causes: Variable 'conn' implicitly has an 'any' type

I have a route like below in which I want to get all posts (like in twitter) from the db. I have separated the likes and images for each post in its own sql table called "post_likes" & "post_images".

After retrieving the posts I want to add the likes for each post and then send it back to the client.

But looping through an array and calling conn.query each time gives me 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.

Why can't typescript determine the type of conn in 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();
  }
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Like T.J. Crowder suggested the problem was the missing type annotation at let conn; but I still don't understand why typescript only throws an error when I try to call conn.query() inside a loop. If someone knows please explain this to me.

I also had to add if (!conn) throw "conn is undefined" to break out of the try & map block.

So I've edited the route to the following:

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda