Executing conn.query repeatedly results in the error message: The variable 'conn' is assumed to have a type of 'any'

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();
  }
});

Answer №1

According to the advice given by T.J. Crowder, the issue was caused by the absence of a type annotation at let conn;. However, it remains puzzling why TypeScript only raises an error when attempting to invoke conn.query() within a loop. If anyone can provide insight into this, I would greatly appreciate it.

In order to address the situation, I found it necessary to insert

if (!conn) throw "conn is undefined"
to escape from the try and map block.

Therefore, I have made adjustments to the route as follows:

router.get("/get/:token", async (req: Request, res: Response) => {
  /**
   * Retrieves all posts 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!!!

    ... 

    /* obtain all posts */
    const queryGetPostsResult = await conn.query(queryGetPosts);
    const getPosts: Array<Post> = [...queryGetPostsResult];

    /* include images and likes for 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 obtain 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 obtain 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();
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting: ng-disabled not function properly in Angular.js

My goal is to only allow the button to be enabled if there is text in the textfield, but for some reason I am unable to make ng-disabled work: <form novalidate> <button type="submit" ng-click="add('+')" ng-disabled="bittext.$invalid ...

Error encountered during decryption with AES encryption: 'ERR_OSSL_EVP_WRONG_FINAL_BLOCK_LENGTH'

I am attempting to decrypt data retrieved from MongoDB using a key and initialization vector (IV) that were stored in an environment function. However, I keep encountering the following error: ERR_OSSL_EVP_WRONG_FINAL_BLOCK_LENGTH app.get("/recieve", as ...

Issue: The browser.newPage function is expecting to receive either accept, deny, or internal-browser-default for download permissions

Utilizing playwright automation, I currently have tests running on browser stack with playwright version 1.37.1. Error: browser.newPage: acceptDownloads: expected one of (accept|deny|internal-browser-default) at src/base/fixtures.ts:62 60 | ...

Tips for running JavaScript code from a file

I'm currently working on launching a webpage in the Firefox browser using Python-Selenium web driver and injecting JavaScript code onto that loaded page. from selenium import webdriver from selenium.webdriver.common.keys import Keys driver= webdriver ...

Switch up div content - advertisements at the top or bottom

An issue has arisen where the ads on a website are currently being displayed at the bottom of the source code, but they should actually be visible at the top. Here is the ad placeholder code: <div id="300_250_placeholder"></div> And here is ...

The compatibility issue between jQuery Tabs and Sliding effect

Hey there, I'm currently working on a website that requires a vertical tab system. I also have an arrow image that shows which tab or thumbnail the user has selected, and it should smoothly slide between the two thumbnails. You can check out the pro ...

Issue with Nodejs redirection functionality when running in a Docker container

My setup includes two docker containers: 1- API 2- Authorization My goal is to redirect user requests from the Authorization container to my API after authentication. Within my authentication container, I have the following code: if (itsAuthenticated) ...

Encountering duplicate entries within the dropdown menu

I have a dropdown menu that fetches values from a JSON file, but there are some repeated values in the JSON file. I want to ensure that these repeated values only appear once. Initially, I was able to filter out the duplicates successfully. However, after ...

Having trouble with the removeEventListener OnDestroy not functioning properly in Angular 6 using Javascript?

I have been experimenting with using the removeEventListener function in my Angular component. I came across a helpful discussion on this topic: Javascript removeEventListener not working ... ngOnInit() { document.addEventListener('v ...

Obtain the Zero-width non-joiner character (‌) using the innerHTML attribute

I am attempting to retrieve a &zwnj; using the innerHTML method The desired output should be This section contains a zero-width‌&zwnj;non-joiner, a non-breaking&nbsp;space &amp; an ampersand However, the current output is: This part c ...

Leveraging ng-class with an Angular $scope attribute

My HTML structure includes: <div class="myDiv"> <div style="width:200px; height:200px;background-image:url('img/200x200/{{largeImg}}.png');" ng-class="{'magictime foolishIn': 1}"> <span> { ...

Manipulate the elements within an array, make changes, and then insert

In the array called newData, I am trying to add one more element with Rank 1. However, the issue is that the Rank value is getting updated for both records. The desired behavior is to have Rank set to 1 for the second record and have the first record' ...

Mesh object circling in the opposite direction of the displayed image

Working on replicating a Flash website using Three.JS and facing difficulty in achieving desired functionality. The goal is to create button images that orbit around the center of the screen, stop when hovered over by the mouse, and open a different locat ...

Next.js allows you to create a single page that corresponds to the root path '/' as well as a dynamic route '/param'

I have a single-page website built with Next.js. The home page, which displays a list of products, is located at route / and the corresponding code can be found in pages/index.js. Each product has an id, allowing users to jump directly to it using /#produc ...

Error in Node.js: Attempting to access properties of undefined

RV = (typeof myresult.CDF.UTILITYTYPE.D2.INSTPARAM[0].VALUE !== 'undefined') ? myresult.CDF.UTILITYTYPE.D2.INSTPARAM[0].VALUE : 'NA'; When attempting to fetch the value from the code above, I encounter an issue. If the key does not exi ...

I encountered an issue with loading an array from session storage in Java Script

I am struggling to restore and reuse a created array in HTML. I attempted using JSON, but it was not successful for me. In the code below, I am attempting to reload items that were previously stored in an array on another page. However, when I try to loa ...

Creating Component Variants for Google Optimize A/B testing in Next.js

I've been attempting to create a component variant in Google Optimize beyond just text or color changes, but I haven't found a suitable method to do so yet. I'm looking for guidance on how to integrate/configure Optimize with my code in orde ...

What could be causing my JSON to update for one API but not the other?

My frustration with the below snippet is preventing me from following the usual advice of "Go to bed and you'll see the error in the morning." The code snippet below contains various tables with an NVD3 chart and some plain p tags that hold data from ...

Discover the secret to applying a gradient shade to the "border" element when it reaches full capacity with Vue's innovative Custom CSS package

Utilizing the package https://www.npmjs.com/package/vue-css-donut-chart#usage-with-all-the-available-props to create a "border" effect around images based on progress has presented a challenge. Specifically, achieving a gradient color for the border when i ...

I am experiencing difficulties accessing the data in React

I am facing an issue where the shells variable appears empty when printed inside the deleteRows function, but it is correctly printed as an array outside the function. I am confused about this behavior. The function is called when a value is deleted. I ha ...