Home > OS >  Argument of type 'string | undefined' is not assignable to parameter of type 'Request
Argument of type 'string | undefined' is not assignable to parameter of type 'Request

Time:12-14

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

CodePudding user response:

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, {
    // ...
  • Related