Reputation: 1536
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
Reputation: 8670
There is a few things you might need to change here.
T
when returning it.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