0

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
4
  • Does this answer your question? Fetch GET Request with custom header? Commented Aug 15, 2022 at 14:05
  • You need a more specific type for the value of (at least) redirect. Try as const, or inlining the options, or an explicit type for requestOptions, or ... Commented Aug 15, 2022 at 14:06
  • my issue is typescript related, it's typescript error... Commented Aug 15, 2022 at 14:06
  • Basically the same question, but in Angular: stackoverflow.com/q/62651724/3001761 Commented Aug 15, 2022 at 14:14

2 Answers 2

3

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
          }
      )
    
Sign up to request clarification or add additional context in comments.

1 Comment

You can also as const either the whole requestOptions object or just the string 'follow': stackoverflow.com/a/62652353/3001761
1

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',
  },
}


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.