Is TypeScript checking in VSCode failing to detect await functions?

I have been working on an app that retrieves weather data based on a user's location, and everything seems to be functioning correctly. However, during the coding process, I keep encountering errors that are being flagged, even though the code runs smoothly.

Below is the snippet of code:

function array_to_comma_sep(array: Array<string>) {
    let output: string = String();
    for (let ele of array) {
        output += ele + ",";
    }
    return output.substring(0, output.length-1);
}

class Feature {
    name: string;
    unit: string;
    constructor(name: string, unit: string) {
        this.name = name;
        this.unit = unit;
    }
}

type GeoLocation = {
    latitude: number;
    longitude: number;
}

async function getWeatherData() {

    const HOURLY_FEATURES: Array<Feature> = [
        new Feature("temperature_2m", "celsius"),
        new Feature("relativehumidity_2m", "%"),
        new Feature("apparent_temperature", "celsius"),
        new Feature("precipitation_probability", "%"),
        new Feature("precipitation", "mm"),
        new Feature("snow_depth", "m"),
        new Feature("visibility", "m")
    ]

    // retrieves user's IP address
    let ip_address: string;
    await $.getJSON("https://api.ipify.org?format=json", data => {
        ip_address = data.ip;
    });
    
    // retrieves user's location
    let location: GeoLocation;
    await $.get(`https://ipapi.co/${ip_address}/latlong/`, data => {
        let [lat, long]: Array<number> = data.split(",").map((num: string) => { return parseFloat(num); });
        location = {
            latitude: lat,
            longitude: long
        }
    });

    // fetches weather information
    let hourly_features = array_to_comma_sep(HOURLY_FEATURES.map((feat: Feature) => { return feat.name }));
    await $.getJSON(`https://api.open-meteo.com/v1/forecast?latitude=${location.latitude}&longitude=${location.longitude}&hourly=${hourly_features}`, data => {
        console.log(data);
    })

}

getWeatherData();

The challenge arises from the VS Code's syntax highlighting - there is a warning message on the line with

await $.getJSON("https://api.ipify.org?format=json", data => {
saying, "Variable 'ip_address' is used before being assigned. ts(2454)".

However, despite this warning, the app's performance remains unaffected. I can see the API response in the console as expected.

Could it be that the TypeScript extension is failing to recognize that the value will be assigned later due to the async function, or am I overlooking something? This is my first encounter with TypeScript.

Moreover, here is the snippet of my HTML code:

<!DOCTYPE html>
<head>  
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js" integrity="sha512-3gJwYpMe3QewGELv8k/BX9vcqhryRdzRMxVfq6ngyWXwo03GFEzjsUm8Q7RZcHPHksttq7/GFoxjCVUjkjvPdw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="app.tsx" type="text/babel"></script>
</head>
<body>
    <div id="container"></div>
</body>

Answer №1

TypeScript is not aware of when the callbacks are invoked, making it unable to predict if the variable will be initialized in time. It is recommended to avoid using callbacks altogether - instead, utilize await to retrieve the value promised:

async function getWeatherData() {
    const HOURLY_FEATURES = [
        new Feature("temperature_2m", "celsius"),
        new Feature("relativehumidity_2m", "%"),
        new Feature("apparent_temperature", "celsius"),
        new Feature("precipitation_probability", "%"),
        new Feature("precipitation", "mm"),
        new Feature("snow_depth", "m"),
        new Feature("visibility", "m")
    ];

    // retrieves user's IP address
    const address: { ip: string } = await $.getJSON("https://api.ipify.org?format=json");
    
    // fetches user's location
    const geo_data: string = await $.get(`https://ipapi.co/${address.ip}/latlong/`);
    const [lat, long] = geo_data.split(",").map(num => parseFloat(num));
    const location: GeoLocation = {
        latitude: lat,
        longitude: long
    };

    // obtains weather information
    const hourly_features = HOURLY_FEATURES.map(feat => feat.name).join(',');
    const data = await $.getJSON(`https://api.open-meteo.com/v1/forecast?latitude=${location.latitude}&longitude=${location.longitude}&hourly=${hourly_features}`);
    console.log(data);
}

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

The drawing library (Google Maps) failed to load

I am looking to integrate drawing mode into Google Maps for my project. Below is the code snippet from my View: <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <me ...

If there is no data defined, then it is necessary for at least one attribute to be present in the

I am encountering an issue while attempting to utilize Google Cloud's Pub/Sub API to send messages to topic subscribers. The error message I am receiving is "If data is undefined, at least one attribute must be present.". My intention is to integrate ...

Is there a way to apply an event function after adding elements through append?

When I click the button, a div is appended inside the body. However, I am trying to make it so that when I click on this newly appended div, an alert message pops up. I have tried implementing this with a highlighted area, but have been unsuccessful. How c ...

Node for Angular forms workflow

I'm on the hunt for workflow nodes with forms that open when the user clicks on them. While I've come across a few options, not all of them are open source. Can you point me towards some open source (simple and basic) alternatives? Here's w ...

What is the best way to obtain a list of all the modules that are currently accessible in AngularJS

When declaring an Angular module, I specify its dependencies as follows: const myModule = angular.module("MyModuleName", ["Dep1", "Dep2", "Dep3"]); Each dependency comes with its own set of dependencies, directives, controllers, etc. Is there a way to qu ...

The initial execution of the getDocs function may encounter some difficulties

Whenever a user connects from localhost:3000/ (which automatically redirects to /profile), I try to fetch all documents from Firebase. However, it does not work on the first attempt. Strangely, upon refreshing the page, it successfully retrieves the docume ...

How can I display an ngx spinner after a delay of 1 second?

I am uncertain about the answer I came across on this platform. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const time = 900; const spinnerLogic = () => { if (this.isRequestServed ...

Pass on only the necessary attributes to the component

I have a simple component that I want to include most, if not all, of the default HTML element props. My idea was to possibly extend React.HTMLAttributes<HTMLElement> and then spread them in the component's attributes. However, the props' ...

following the history.back() function call, the subsequent codes are executed

<?php $ok_register = 0; if($ok_register != 1) { ?> <javascript type="text/javascript"> alert("1"); history.back(); </javascript> <?php } ?> <javascript type="text/javas ...

Conquering Challenges Across Multiple Disciplines

Is there a solution to solving the cross domain issues that arise when trying to fetch data from a different web server on the client-side, in violation of the Same Origin policy? ...

Issue: The error message "TypeError: React.createContext is not a function" occurs when using Next.js 13 alongside Formik with TypeScript

I'm currently working on creating a form using Formik in NextJs 13 (Typescript). However, the form I designed isn't functioning properly. To troubleshoot, I added code snippets from Formik's examples as shown below. Unfortunately, both my fo ...

I'm having trouble with my useState in React/NEXTjs because it's not adding onto the result of a socket.io event from the server, it's simply

Frameworks used: Next.js, Socket.io, React I am currently working on a straightforward messaging application. The main concept involves emitting a message typed by a user, sending that message to the server, and then broadcasting it back to all clients th ...

The initial transition in offcanvas on bootstrap 5 is not appearing when a placement is dynamically added

I am currently working on triggering an Offcanvas with JS and making the placement configurable. The issue arises when attempting to dynamically set the offcanvas-end class to the offcanvas element, as it does not transition smoothly the first time it is t ...

Importing JWT in ES6SyntaxCreating ES6 imports

I'm currently developing a nodeJS web application and utilizing JWT for authentication. My code is all written in ES6 modules, so I wanted to import JWT the same way. However, it seems that the package does not fully support this method yet. Since I&a ...

webpack encountered an issue: The configuration.module contains an unidentified property 'loaders'

Upon starting the server with npm run start, I encountered the following error message: ✖ 「wds」: Invalid configuration object. Webpack has been initialized using a configuration object that does not comply with the API schema. - Configuration cont ...

A problem arises in Next.js when CSS is not rendering properly during Server Side Rendering

After creating my next.js application using the command npx create-next-app, I realized that the styles from the imported .css files are rendering correctly on Client Side Render but not on Server Side Render. The Next.js documentation states that importe ...

By default, Nuxt 2.15.7 is automatically installed when you create a new Nuxt app

I am looking to develop a Nuxt app (version 3) using Vue. However, when I run the command npm create nuxt-app@version mousa, it automatically installs Nuxt2. How can I install Nuxt3 instead with this command? ...

Is there a method to access the variable name of v-model from a child component in the parent component?

In the scenario below, I am customizing a vue radio component and using the model option to retrieve the v-model value, which is expected to be a string '1'. Is there a way for me to access its variable name 'radio1' in the child compon ...

Tips for extracting key values from an array of objects in Typescript

I am working with an array called studyTypes: const studyTypes = [ { value: "ENG", label: "ENG-RU", }, { value: "RU", label: "RU-ENG", }, ]; Additionally, I have a state variable set ...

The function of edit does not exist

I'm currently working on creating a discord bot that will send a message to a specific channel upon startup. Initially, I was able to send the message to the designated channel without any issues. However, when I attempted to edit the message, an erro ...