如何标记将函数的返回类型标记为自定义类型的承诺

时间:2017-06-16 17:45:40

标签: typescript bluebird

我有一个看起来像这样的代码片段

import * as Promise from 'bluebird';
import {Response} from '../commonInterfaces/httpService';

getCall(url: string, accessToken: string, extraHeaders: object): Promise<Response> {
    let headers = this.getHeaders(accessToken, extraHeaders);
    return new Promise((resolve, reject) => {
        request({
            url: url,
            method: "GET",
            withCredentials: false,
            json: true,
            headers: headers
        }, (err: Error, response: Response) => {
            if (err) {
                reject(err)
            } else {
                resolve(response)
            }
        });
    });
}

和Response是一个接口

interface Response {statusCode: number, body: object}

我收到以下错误

[ts]
Type 'Bluebird<{}>' is not assignable to type 'Bluebird<Response>'.
Type '{}' is not assignable to type 'Response'.
Property 'statusCode' is missing in type '{}'.

可能是什么问题?

1 个答案:

答案 0 :(得分:1)

似乎编译器不会通过调用resolve(response)来推断类型 您可以通过自己指定通用约束来“帮助”它:

return new Promise<Response>((resolve, reject) => { ... });