skip to Main Content

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?

2

Answers


  1. 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
    

    typescript playground

    Thank you @JaromandaX for the discussion.

    Login or Signup to reply.
  2. Generally, instead of typing functions with CallableFunction, we type them like this: ((...) => ...) as you can see in the typescript documentation: https://www.typescriptlang.org/docs/handbook/2/functions.html#function-type-expressions

    Since asynchronous functions return a Promise, the type "any" will fit for them too.

    This is how you can fix it:

    export const provide = async (callables: (() => any)[]) => {
        for (const callable of callables) {
            await callable()
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search