我开始在我的 nodejs 项目中使用 Typescript。为了访问一些外部 API,我使用 node-fetch 来发出请求。在设置 PUT 请求时,会弹出一个错误,指出给定的正文不可分配给 type RequestInit
:
错误:
Error:(176, 28) TS2345:Argument of type '{ headers: Headers; method: string; body: MyClass; }' is not assignable to parameter of type 'RequestInit'.
Types of property 'body' are incompatible.
Type 'MyClass' is not assignable to type 'BodyInit'.
Type 'MyClass' is not assignable to type 'ReadableStream'.
Property 'readable' is missing in type 'MyClass'.
我的课:
class MyClass {
configId: string;
adapterType: string;
address: string;
constructor(configId: string, adapterType: string, address: string) {
this.configId = configId;
this.adapterType = adapterType;
this.address = address;
}
// some methods
}
调用:
let body = new MyClass("a", "b", "c")
let url = config.url + "/dialog/" + dialogId
let headers = new Headers()
// Append several headers
let params = {
headers: headers,
method: "PUT",
body: body
}
return new Promise((resolve, reject) => {
Fetch(url, params) // <-- error is shown for params variable
.then(res => {
// Do stuff
resolve(/*somevalue*/)
})
}
我应该如何使 body 对象兼容?