10

I am trying to use the Fetch API in TypeScript, but for some reason I am getting

Type 'string' is not assignable to type 'RequestMode'.

Here is my code

export class MainService{
  constructor(){}
  request(requestObj){
    if (!requestObj.url) {
      return 'Please provide the end point url'
    }
    else {
     let requestParam = {
        method: requestObj.method ? requestObj.method : 'GET',
        headers: new Headers(),
        mode: 'cors'
      };
      fetch(endPointHost+requestObj.url,requestParam).then(function(resp){
                                        //^^^ error thrown here
        resp.json();
      })
    }
     console.log(" Reached request");
  }

}

The error reported is

TS2345: Argument of type '{ method: any; headers: Headers; mode: string; }' is not assignable to parameter of type 'RequestInit'. Types of property 'mode' are incompatible. Type 'string' is not assignable to type 'RequestMode'.

8
  • 4
    Does let requestParam: RequestInit = { … work? Commented Dec 17, 2017 at 7:28
  • 1
    requestObj.url === undefined && requestObj.url === '' is a buf a variable cannot be undefined and '' at the same time. try if (!requestObj.url) { ... } instead Commented Dec 17, 2017 at 7:31
  • @Ryan thanks Sir it worked, i am trying to find out the reason why it worked Commented Dec 17, 2017 at 7:44
  • @GuyWhoKnowsStuff I completely agree with you, that was my mistake, have make the change Commented Dec 17, 2017 at 7:45
  • sarcasm? :) i wasnt trying to answer just saw a bug Commented Dec 17, 2017 at 7:47

2 Answers 2

18

This worked for me: mode: 'cors' as RequestMode,

Sign up to request clarification or add additional context in comments.

Comments

9

The problem here is that requestParam could potentially be modified in an way that it does not respect RequestInit interface later. You can either declare that requestParam implements RequestInit at creation:

let requestParam: RequestInit = {
    method: requestObj.method ? requestObj.method : 'GET',
    headers: new Headers(),
    mode: 'cors'
};

or put request parameters directly inside the fetch call:

fetch(endPointHost+requestObj.url, {
    method: requestObj.method ? requestObj.method : 'GET',
    headers: new Headers(),
    mode: 'cors'
}).then(function(resp){
    resp.json();
})

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.