DrewB
DrewB

Reputation: 1536

Typescript function parameter as function or type

I am working with a Typescript library authored by someone else. In one of the functions, it takes a parameter that can be a function or a value like:

function returnDefault<T>(defaultVal: T | () => T): T {
    if(typeof defaultVal === 'function') {
        return defaultVal();
    }
    return defaultVal;
}

When attempting to use this function, I am getting a Typescript error "This expression is not callable. Not all constituents of type '(() => T) | (T & Function)' are callable. Type 'T & Function' has no call signatures." This error appears on the third line (return defaultVal();). What am I doing wrong here or how can I fix this error?

Upvotes: 0

Views: 210

Answers (1)

Nicolas
Nicolas

Reputation: 8670

There is a few things you might need to change here.

  • When defining a callback as a type, you need to enclose it in parenthesis.
  • You might have to cast your variable as a function when calling it, and as a T when returning it.
  • You might have to use the call method rather than parenthesis directly.

Here is working, untested example.

function returnDefault<T>(defaultVal: T | (() => T)): T {
    if(typeof defaultVal === "function") {
        return (defaultVal as Function).call({});
    }
    return defaultVal as T;
}

The syntax seams to be valid in the playground.

Upvotes: 1

Related Questions