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

How to Typescript fetch

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’.

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

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.

>Solution :

Does this help?

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

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

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