I'm encountering difficulty translating the numerous function overloading examples from SO to my specific scenario:
const createAccessor = <T, >(defaultValue: T) => {
const value = defaultValue
function fetch(): T;
function fetch<TPart>(selector?: (obj: T) => TPart) {
if (selector)
return selector(value)
return value
}
return { fetch }
}
const obj = createAccessor({
part1: { a: 1, b : 2 },
part2: { name: 'Hans' }
})
// Here is how I aim to utilize it:
const fullObject = obj.fetch() // should return T
const part1 = obj.fetch(o => o.part1) // should return TPart
(also available on ts-playground)
When I remove the initial overload, the code compiles but the resulting return types are incorrect. What might be the issue here?