Issue
I have this code:
export const provide = async (callables: CallableFunction[]) => {
for (const callable of callables) {
await callable()
}
}
A callable
may or may not be async.
I've tried typing it like this:
export const provide = async (callables: CallableFunction[] | Promise<CallableFunction>[]) => {
for (const callable of callables) {
await callable()
}
}
But vscode gives me the error:
This expression is not callable. No constituent of type 'CallableFunction | Promise' is callable.
How do I type an array of CallableFunction's that may or may not be async?
Solution
CallableFunction
includes any would-be async
functions -
const provide = async (callables: CallableFunction[]) => {
for (const callable of callables) {
await callable()
}
}
provide([
() => { console.log("hello") },
async () => {
await new Promise(r => setTimeout(r, 1000))
console.log("world")
},
])
hello
world
According to your comment, it sounds like the CallableFunction
interface is not suitable for your needs -
const provide = async (callables: Array<() => void | Promise<void>>) => {
for (const callable of callables) {
await callable()
}
}
Now you can see a more explicit type -
Answered By - Mulan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.