Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is TypeScript reporting that "'string' is not assignable to type 'RequestMode'"?

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

like image 419
brk Avatar asked Dec 17 '17 07:12

brk


People also ask

How do I fix the argument of type string is not assignable to parameter of type never?

The error "Argument of type is not assignable to parameter of type 'never'" occurs when we declare an empty array without explicitly typing it and attempt to add elements to it. To solve the error, explicitly type the empty array, e.g. const arr: string[] = []; .

Is not assignable to type string Ts?

The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.

Is not assignable to parameter of type?

The error "Argument of type string | undefined is not assignable to parameter of type string" occurs when a possibly undefined value is passed to a function that expects a string . To solve the error, use a type guard to verify the value is a string before passing it to the function.


1 Answers

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

like image 89
ianhowe76 Avatar answered Nov 14 '22 21:11

ianhowe76