You can see a demo in this playground.
I've made a simple generic type which can represent either a variable or a function that returns a variable. But, unfortunately, it doesn't work with a typical typeof arg === 'function'
check. It produces the following error:
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 make it work without using 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 // error here
}
const isFunction = (arg: any): arg is Function => typeof arg === 'function'
function correct_2<T>(arg: Initializer<T>) {
return isFunction(arg) ? arg() : arg
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…