使用自定义承诺作为泛型类型

时间:2016-04-13 08:46:03

标签: typescript promise bluebird

我有一个环境TypeScript模块代表一个支持任何Promises / A +库的库:

interface Test {
  funcName():Promise<string>;
}

所以我需要调整它,以便在声明级别上访问任何promise库的协议:

interface Test<P> {
  funcName():P<string>;
}

但在我使用它之前,TypeScript会立即抱怨:Type 'P' is not generic

请注意,我不能将自定义承诺库包含在与Test相同的文件中,因为我必须从另一个模块中传入它。

如果我将代码更改为:

interface AnyPromise<T, P extends Promise<T>> {
}

interface Test<P> {
    funcName():AnyPromise<string, P<string>>;
}

它还会在此部分中抱怨error TS2315: Type 'P' is not generic.P<string>

最后,我需要能够做到这样的事情:

import * as promise from 'bluebird'; // from Bluebird ambient declarations 
import {Test} from 'test';

var Test<promise> t; // plus initialize it;

t.funcName().finally(())=>{
}); // NOTE: 'finally' is to be visible from Bluebird (doesn't exist in ES6 Promise)

再次澄清,我使用Bluebird作为一个例子,因为我需要一个解决方案来支持任何一个promise库,而不是一个特定的。

1 个答案:

答案 0 :(得分:5)

这需要更高的kinded类型才能在TypeScript中着陆。跟踪它们的问题在这里:

https://github.com/Microsoft/TypeScript/issues/1213

截至2016年4月,尚未实现。

您可以使用产品类型对其中某些内容进行近似,但需要修改PromiseLike类型,并且您需要在库中使用then的任何时候显式传递type参数:

interface HKPromiseLike<T> {
    then<TResult, P>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): P & HKPromiseLike<TResult>;
    then<TResult, P>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): P & HKPromiseLike<TResult>;
}

class Wrapper<T, P> {
    constructor(public p:P & HKPromiseLike<T>) {}

    map<U>(f:(t:T) => U) {
        var res = this.p.then<U, P>(f)
        var w = new Wrapper(res);
        return w
    }
}

要专门化这个包装器,必须使用class / extends。

class Specialized<T> extends Wrapper<T, SomePromise<T>> { }
相关问题