【发布时间】:2017-03-21 18:26:17
【问题描述】:
我正在尝试为节点的 Google Maps 帮助程序模块编写声明,但我遇到了库期望的 PromiseConstructorLike 问题,并正确返回它的“PromiseLike”实例方法(根据https://googlemaps.github.io/google-maps-services-js/docs/module-@google_maps.html):
Promise function <optional> Promise constructor (optional).
所以我做了(精简到有趣的部分):
declare namespace GoogleMaps {
export interface CreateClientOptions<T> {
/** Promise constructor (optional). */
Promise?: T;
}
export interface GoogleMapsClient<T> {
directions<U>(query, callback?: ResponseCallback<U>): RequestHandle<U, T>;
}
export interface Response<U extends any> {
headers: any;
json: U;
status: number;
}
export interface RequestHandle<U, T extends PromiseLike<Response<U>>> {
asPromise(): T;
cancel(): void;
finally(callback: ResponseCallback<U>): void;
}
export type ResponseCallback<U> = (err: Error, result: Response<U>) => void;
export function createClient<T extends PromiseConstructorLike>(options: CreateClientOptions<T>): GoogleMapsClient<T>;
}
declare module '@google/maps' {
export = GoogleMaps
}
当然不行,比如我用createClient中的Bluebird作为
import * as bluebird from 'bluebird'
import { createClient } from '@google/maps'
createClient({ Promise: bluebird }).directions({}).asPromise()/** no "then" here, just the static methods from Bluebird, like Bluebird.all */
那么问题来了:
我是否可以提示 asPromise 方法从 bluebird 返回实例方法(然后,catch,finally,reduce,timeout 等),而无需手动扩展 RequestHandle 接口?强>
更多信息(lib.d.ts 声明):
PromiseConstructorLike 是:
declare type PromiseConstructorLike = new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) => PromiseLike<T>;
PromiseLike 是:
interface PromiseLike<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then(
onfulfilled?: ((value: T) => T | PromiseLike<T>) | undefined | null,
onrejected?: ((reason: any) => T | PromiseLike<T>) | undefined | null): PromiseLike<T>;
}
【问题讨论】:
标签: typescript typescript-typings typescript2.0