2016-10-19 36 views
0

打字稿V2.0.2 運行埃爾卡皮坦10.11.6我該如何聲明一個可選地接受回調的函數,並且只有在沒有回調的情況下才返回一個Promise?在Mac上

我有一個執行異步操作, 和單一的功能:

  • 要麼需要一個回調,並沒有返回,調用回調 後,
  • 或不接受回調,並返回一個承諾,稍後解決。

看來,我已經有類似的代碼工作, (見https://github.com/psnider/mongodb-adaptor/blob/master/src/ts/MongoDBAdaptor.ts) 但現在,這是失敗的, ,我想不通爲什麼!

// these declarations look correct to me, the caller uses one or the other 
declare abstract class SlimDocumentDatabase<T> { 
    create(obj: T): Promise<T> 
    create(obj: T, done: (error: Error, result?: T) => void): void 
} 

class SlimAdaptor<DocumentType> implements SlimDocumentDatabase<DocumentType> { 
    create(obj: DocumentType, done?: (error: Error, result?: DocumentType) => void) : void | Promise<DocumentType> { 
     if (done) { 
      done(undefined, obj) 
      return 
     } else { 
      return Promise.resolve<DocumentType>(obj) 
     } 
    } 
} 

我能得到這個從創造的實現(除去返回類型規格)進行編譯,通過與任何替換它們。但是這似乎是錯誤的!

這裏是打字稿遊樂場代碼: http://www.typescriptlang.org/play/index.html#src=declare%20abstract%20class%20SlimDocumentDatabase%3CT%3E%20%7B%0A%20%20%20%20create(obj%3A%20T)%3A%20Promise%3CT%3E%0A%20%20%20%20create(obj%3A%20T%2C%20done%3A%20(error%3A%20Error%2C%20result%3F%3A%20T)%20%3D%3E%20void)%3A%20void%0A%7D%0A%0A%0Aclass%20SlimAdaptor%3CDocumentType%3E%20implements%20SlimDocumentDatabase%3CDocumentType%3E%20%7B%0A%20%20%20%20%2F%2F%20create(obj%3A%20DocumentType)%3A%20Promise%3CDocumentType%3E%0A%20%20%20%20%2F%2F%20create(obj%3A%20DocumentType%2C%20done%3A%20ObjectCallback%3CDocumentType%3E)%3A%20void%0A%20%20%20%20create(obj%3A%20DocumentType%2C%20done%3F%3A%20(error%3A%20Error%2C%20result%3F%3A%20DocumentType)%20%3D%3E%20void)%20%3A%20void%20%7C%20Promise%3CDocumentType%3E%20%7B%0A%20%20%20%20%20%20%20%20if%20(done)%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20done(undefined%2C%20obj)%0A%20%20%20%20%20%20%20%20%20%20%20%20return%0A%20%20%20%20%20%20%20%20%7D%20else%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20Promise.resolve%3CDocumentType%3E(obj)%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%7D%0A%0A%7D%0A

回答

相關問題