I have a function identityOrCall that either calls the function given to it, or returns the value. value is a generic type.
function identityOrCall <T>(value: T): T {
if (typeof value === 'function')
return value()
else
return value
}
identityOrCall(() => 'x') // -> 'x'
The line identityOrCall(() => 'x') appears to pass the compiler's type checking.
Why? Shouldn't it give an error?
If identityOrCall is passed a function, I would expect the generic type T to be set to Function and that identityOrCall should return a Function type.
Instead I'm able to pass a Function type as an argument and have identityOrCall return a string type.
Why is this? It appears inconsistent to me, but I must be missing something.
identityOrCall(() => 'x')will not return an error (why would it?) in this caseTwill be() => stringwhich is a valid typeidentityOrCallto return the same type as it's argument. If given aFunctiontype as an argument I would expect it to return aFunctiontype.