0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.