Suppose we have the following function:
function test<S, T>(obj: S, prop: keyof S, mapper?: (value: S[keyof S]) => T): S[keyof S] | T {
return typeof mapper === 'function'
? mapper(obj[prop])
: obj[prop];
}
If then I use it without the mapper argument, the type of the return value is not deduced properly:
const value = test({ a: 'stringValue' }, 'a'); // value is of type "unknown"
But if I provide an identity function as the third parameter, it is deduced correctly:
const value = test({ a: 'stringValue' }, 'a', x => x); // value is of type "string"
How should the test function be typed so when we don't provide the mapper argument, the return value's type is deduced correctly?