Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda