Home > Software engineering >  Quickest and simplest way to convert fetch JavaScript to work in TypeScript project
Quickest and simplest way to convert fetch JavaScript to work in TypeScript project

Time:08-16

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

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

CodePudding user response:

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
          }
      )
    

CodePudding user response:

The easiest way is to specify the type of your requestOptions object:

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


  • Related