Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Argument of type 'string | undefined' is not assignable to parameter of type 'RequestInfo'

I’m trying to convert existing React project from JavaScript to TypeScript. I have this function:

  const isSad = async (value: string) => {
    return await fetch(process.env.REACT_APP_TEXT_TO_EMOTION_API, {
      method: "POST",
      headers: {
        apikey: process.env.REACT_APP_TEXT_TO_EMOTION_API_KEY,
      },
      body: value,
    })
      .then(data => {
        return data.json();
      })
      .then(data => {
        // Checking api response and returning true if sad or false if not.
        return data.Sad > 0.49
      })
      .catch((error) => {
        console.log("logging the error in catch", error);
      });
  };

Nothing is glowing red in VS Code but when I try to compile I get the following error:

Argument of type 'string | undefined' is not assignable to parameter of type 'RequestInfo'.
  Type 'undefined' is not assignable to type 'RequestInfo'.  TS2345

I tried this solution but when I try to add <any> in front of process.env it reads it as JSX and everything turns red

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’ll have to make sure your env variable isn’t undefined before you use it.

const isSad = async (value: string) => {
    const apiAddress: string|undefined = process.env.REACT_APP_TEXT_TO_EMOTION_API

    if (!apiAddress) throw 'API address not defined'

    // `apiAddress` is of type string at this point
    return await fetch(apiAddress, {
    //...

or use a type assertion with the newer as keyword (since the original syntax clashes with jsx), but this is less type-safe

    return await fetch(process.env.REACT_APP_TEXT_TO_EMOTION_API as string, {
    // ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading