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];
}
如果我在没有mapper
参数的情况下使用它,则返回值的类型推导不正确:
const value = test({ a: 'stringValue' }, 'a'); // value is of type "unknown"
但如果我提供一个恒等式函数作为第三个参数,则可以正确推导:
const value = test({ a: 'stringValue' }, 'a', x => x); // value is of type "string"
test
函数应该如何类型化,以便在不提供mapper
参数的情况下,正确推导返回值的类型?