如何声明一个函数,它可以选择接受回调,并且 returns 只有在没有回调的情况下才是 Promise?
How can I declare a function that optionally takes a callback, and returns a Promise only if there is no callback?
TypeScript v2.0.2
Mac 运行 El Capitan 10.11.6
我有一个执行异步操作的函数,
和:
- 要么接受回调,return什么都没有,调用回调
后来,
- 或者不接受回调,return是一个 Promise,稍后解决。
看来我也做过类似的代码工作,
(参见 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)
}
}
}
我可以通过从 create() 的实现中删除 return 类型规范,将它们替换为 any 来编译它。但这似乎是错误的!
已在 https://github.com/Microsoft/TypeScript-Handbook/issues/427#issuecomment-257648196
中回答
简而言之,class 定义中的代码必须包括声明和实现。
在上面的代码示例中,链接到 TypeScript Playground,
取消注释 class 的前两行,代码将编译。
TypeScript v2.0.2 Mac 运行 El Capitan 10.11.6
我有一个执行异步操作的函数, 和:
- 要么接受回调,return什么都没有,调用回调 后来,
- 或者不接受回调,return是一个 Promise,稍后解决。
看来我也做过类似的代码工作, (参见 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)
}
}
}
我可以通过从 create() 的实现中删除 return 类型规范,将它们替换为 any 来编译它。但这似乎是错误的!
已在 https://github.com/Microsoft/TypeScript-Handbook/issues/427#issuecomment-257648196
中回答简而言之,class 定义中的代码必须包括声明和实现。
在上面的代码示例中,链接到 TypeScript Playground, 取消注释 class 的前两行,代码将编译。