2017-04-10 74 views
0

我试图在Typescript中取消我的async方法调用。Typescript:Promise的子类/扩展:不引用Promise兼容的构造函数值

要做到这一点,我创建了一个新的承诺类型,它继承了Promise

class CancelablePromise<T> extends Promise<T>{ 

    private cancelMethod:() => void; 
    constructor(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void, cancelMethod:() => void) { 
     super(executor); 
     this.cancelMethod = cancelMethod; 
    } 

    //cancel the operation 
    public cancel() { 
     if (this.cancelMethod) { 
      this.cancelMethod(); 
     } 
    } 
} 

但是,当我试图使用它:

async postFileAjax<T>(file: File): CancelablePromise<T> { ... } 

我得到的错误:

Error Build:Type 'typeof CancelablePromise' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.

如果我使用类型声明并返回CancelablePromise ,像这样然后它编译:

async postFileAjax<T>(file: File): Promise<T> { 
    ... 
    return CancelablePromise(...); 
} 

我做错了什么?我看到在ES6中,您可以继承Promise(请参阅stackoverflow question),所以我期望它也可以在TypeScript中使用。

使用打字稿2.1和定位ES5

+0

不能扩展内建类型,除非你的目标'es6'(或以上) –

+0

如果你有一个参考,然后这是公认的答案;) – Julian

+0

试试这个:[扩展错误在发射ES5时不起作用](https://github.com/Microsoft/TypeScript/issues/10166) –

回答

0

的错误信息是不是在第一完全清楚我的,但构造方法的签名应该是相同的Promise构造。因此,这将编译:

class CancelablePromise<T> extends Promise<T>{ 

    public cancelMethod:() => void; 
    constructor(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) { 
     super(executor); 

    } 

    //cancel the operation 
    public cancel() { 
     if (this.cancelMethod) { 
      this.cancelMethod(); 
     } 
    } 
} 

,并呼吁:

async postFileAjax<T>(file: File): CancelablePromise <T> { 

    var promiseFunc = (resolve) => { resolve() }; 
    var promise = new CancelablePromise<T>(promiseFunc); 
    promise.cancelMethod =() => { console.log("cancel!") }; 

    return promise; 
} 
相关问题