【发布时间】:2019-02-28 22:44:05
【问题描述】:
我有一个可以返回同步或异步结果的函数
type HookHandler<T> = (context: MyClass<T>) => boolean | Promise<boolean>;
以及一个接受该函数列表的类
class MyClass<T> {
constructor(private handlers: Array<HookHandler<T>>) {
}
public invokeHandlers() : boolean | Promise<boolean> {
// invoke each handler and return:
// - Promise<boolean> if exist a handler that return a Promise<T>
// - boolean if all handlers are synchronous
}
}
我想知道是否有机会让打字稿根据给定的处理程序推断invokeHandlers() 的返回类型。考虑到所有的处理程序都是在设计时声明的:
const myClassSync = new MyClass<MyType>([
(ctx) => true,
(ctx) => false
]);
const myClassAsync = new MyClass<MyType>([
async (ctx) => Promise.resolve(true),
async (ctx) => Promise.reject()
]);
const myClassMix = new MyClass<MyType>([
async (ctx) => Promise.resolve(true),
(ctx) => true
]);
我可以在没有显式转换的情况下使invokeHandlers() 的返回类型依赖于当前给定处理程序的类型吗?比如
// all handlers are sync, infer boolean
const allHandlersAreOk: boolean = myClassSync.invokeHandlers()
// all handlers are async, infer Promise<boolean>
const allAsyncHandlersAreOk: Promise<boolean> = await myClassAsync.invokeHandlers()
// at least one handler is async, infer Promise<boolean>
const allMixedHandlersAreOk: Promise<boolean> = await myClassMix.invokeHandlers()
我显然可以返回一个简单的Promise<boolean>,但我会失去在同步上下文中调用invokeHandlers() 的可能性,它希望避免这种情况。
有什么建议或其他设计选择来解决这个问题吗?谢谢!
【问题讨论】:
-
我可能有一个解决方案给你,但你的代码没有
T参数的结构依赖,所以我打算排除它。 -
泛型是从真实代码中复制粘贴过来的,这只是一个简化
标签: typescript design-patterns promise async-await conditional-types