2017-04-10 18 views
0

asyncメソッド呼び出しをTypescriptで取り消そうとしています。これを行うには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でサブクラスPromisestackoverflow questionを参照してください)を参照してください、私はそれもタイプスクリプトで期待しています。

活字体2.1を使用して、エラーメッセージが最初に私に完全に明確ではなかった

+0

あなたが拡張することはできませんビルトインタイプのあなたはそのための参照を持っている場合は、その後、 'es6'(またはそれ以上) –

+0

を対象としない限り、それは受け入れられた答えです;) – Julian

+0

これを試してください:[ES5を出してもエラーからの拡張はできません](https://github.com/Microsoft/TypeScript/issues/10166) –

答えて

0

ES5標的が、コンストラクタのシグネチャは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; 
} 
関連する問題