I want to create a helper function isCallback
that returns whether a function is callable.
I have a type that can either be true
or a callback with a specific argument. In my current code, I have lots of checks like typeof foo === 'function'
and I want to refactor those with the isCallback
function.
I created this helper function isCallback
:
export const isCallback = (maybeFunction: unknown): boolean =>
typeof maybeFunction === 'function'
My problem is that when I use it TypeScript is confused:
if(isCallback(foo)) {
foo(myArgs) // Error here
}
and complains with:
This expression is not callable.
Not all constituents of type 'true | ((result: Result) => void)' are callable.
Type 'true' has no call signatures.
How can I create a function that returns true
if the variable is callable and TypeScript knows about it, too?
As @jonrsharpe pointed out, using type predicates works.
export const isCallback = (
maybeFunction: true | ((...args: any[]) => void),
): maybeFunction is (...args: any[]) => void =>
typeof maybeFunction === 'function'