Home > front end >  How to Typescript fetch
How to Typescript fetch

Time:10-21

I just started to learn Typescript and I'm trying to convert a utility file to Typescript. I fixed most of the errors but I'm confused about the error I received from a fetch command.

fetch(process.env.REACT_APP_API_URL)

This gives me the following error:

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

What's confusing me is that I have another fetch somewhere else that isn't giving any errors:

fetch(`https://somerandomapi.io/?token=${process.env.REACT_APP_API_TOKEN}`)

How do I fix the error here? When I search for TS2345, the issues don't seem that similar to me yet but that's probably because I'm still new to Typescript. Any help would be appreciated.

Update

When I updated my code to

fetch(`${process.env.REACT_APP_API_URL}`)

The error went away. Although I feel like this is not the solution I should be doing.

CodePudding user response:

Does this help?

fetch(new URL(process.env.REACT_APP_API_URL!))

(Assuming that it is a URL from the name of the variable)

  • Related