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

Quickest and simplest way to convert fetch JavaScript to work in TypeScript project

What’s the simplest way to get this piece of code working in TypeScript project?

var requestOptions = {
  method: 'GET',
  body: raw,
  redirect: 'follow',
  headers: {
    'x-mock-response-code': '204',
  },
}

fetch(
  'https://abcd.mock.pstmn.io/token',
  requestOptions
)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error))

I get this error that won’t let me compile:

enter image description here

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

Argument of type '{ method: string; body: string; redirect: string; headers: { 'x-mock-response-code': string; }; }' is not assignable to parameter of type 'RequestInit'.
   Types of property 'redirect' are incompatible.
     Type 'string' is not assignable to type 'RequestRedirect | undefined'.ts(234

>Solution :

Since you assigned a plain object to requestOptions without specifying a type, TypeScript has inferred what type it should be.

That type thinks redirect is a string, but fetch expects it to be one of a specific selection of strings.

When you later pass the object to fetch, TypeScript thinks the value you used can be any string and you get an error.

You have a couple of options here:

  • Be explicit about the types

    That way when you pass the object to fetch it will be of the RequestInit type instead of the inferred type you are currently passing.

      var requestOptions: RequestInit = {
    
  • Don’t use the intermediate variable

    If you assign the object directly to the argument, then TypeScript can compare it directly instead of creating a type and then comparing that type.

      fetch(
          'https://abcd.mock.pstmn.io/token',
          {
              // options here
          }
      )
    
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