Currently, I am diving into a codebase packed with numerous asynchronous API calls that include success
options in their parameters. Here is a snippet:
declare function foo(_: {
success?: (_: string) => void,
fail?: () => void,
}): void
declare function bar(_: {
success?: (_: string) => void,
fail?: () => void,
src?: string
}): void
declare function baz(_: {
success?: (_: string) => void,
fail?: () => void,
expired: number
}): void
declare function foobar(_: {
success?: (_: string) => void,
fail?: () => void,
token: string,
state: boolean
}): void
My aim is to convert all these functions into promises using the following code:
interface Cont<R> {
fail?: () => void
success?: (_: R) => void
}
interface Suspendable<O> {
(option: O): void
}
function suspend<R, O extends Cont<R>>(fn: Suspendable<O>) {
return async (opt: Omit<Omit<O, "success">, "fail">) => await new Promise<R>((resolve, _) => fn({
...opt,
success: it => resolve(it),
fail: ()=> resolve(undefined)
} as O )) // if any chance, I'd like to omit the `as O` but forgive it for now
}
(async () => {
let _foo = await suspend(foo)({}) // good
let _bar = await suspend(bar)({}) // good
let _baz = await suspend(baz)/* compile error here */ ({ expired: 100})
})()
Is there anything in TypeScript that I might have overlooked to assist me in capturing the true type of the O
in the fn
parameter? This way, I can properly constrain the parameters and eliminate compiler errors.