2017-05-16 6 views
0

내 nodejs 프로젝트에 Typescript를 사용하기 시작했습니다. 일부 외부 API에 액세스하기 위해 node-fetch를 사용하여 요청합니다.node-fetch를 사용할 때 요청 본문 유형을 RequestInit 또는 BodyInit과 호환 가능하게 만드는 방법은 무엇입니까?

오류 :

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

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 
} 

호출 :

풋 요청을 설정하는 동안 오류가 주어진 몸이 RequestInit을 입력 할 할당 할 수없는 것을 말하고, 팝업
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*/) 
    }) 
} 

본문 개체를 어떻게 호환 가능하게해야합니까?

답변

0

두 가지 가능한 접근법을 생각해 볼 수 있습니다. 하나는 특정 방식으로 헤더를 설정하여 body 유형을 보완하는 것입니다.

다른 생각은 클래스의 인스턴스가 적절한 본문 유형이 아닐 수 있다는 것입니다. 그것을 현혹시킬 수 있습니까?

업데이트 : 나도 RequestInit와 이상한 오류가 있고, 그것은 같이, (당신이 '의 PARAMS을'이라고 부르는) 옵션의 종류를 지정하여 객체를 해결되었습니다 :

let params: RequestInit = { 
    ... 
}