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

Using a custom promise as a generic type

我有一个环境 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 库,而不是特定的。

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

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

截至 2016 年 4 月,还不可能。

你可以用产品类型来近似它的一些,但它需要修改 PromiseLike 类型,你需要在你使用 then 时明确传递类型参数图书馆:

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>> { }