You can check out a demonstration on this interactive platform.
In creating a simple generic type that represents either a variable or a function returning a variable, there was an issue with the typical typeof arg === 'function'
check. The error message displayed was as follows:
This expression is not callable.
Not all constituents of type '(() => T) | (T & Function)' are callable.
Type 'T & Function' has no call signatures.
Is there a way to resolve this without resorting to using a type guard function?
type Initializer<T> = T | (() => T)
function correct(arg: Initializer<string>) {
return typeof arg === 'function' ? arg() : arg
}
function wrong<T>(arg: Initializer<T>) {
return typeof arg === 'function' ? arg() : arg // issue here
}
const isFunction = (arg: any): arg is Function => typeof arg === 'function'
function correct_2<T>(arg: Initializer<T>) {
return isFunction(arg) ? arg() : arg
}