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
'.
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[] = []; .
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.
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.
This worked for me: mode: 'cors' as RequestMode,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With