Using a custom promise as a generic type

倖福魔咒の 提交于 2019-12-04 02:56:05

This requires higher kinded types to land in TypeScript. The issue that tracks them is here:

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

As of April 2016, its not yet possible.

You can approximate some of it with product types, but it needs a modification of the PromiseLike type and you will need to explicitly pass the type parameter around any time you use then within your library:

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

To specialize this wrapper, you must use class/extends.

class Specialized<T> extends Wrapper<T, SomePromise<T>> { }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!