I can't transfer the many function overloading examples on SO to my use case:
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' }
})
// This is how i want to use it:
const fullObject = obj.fetch() // should return T
const part1 = obj.fetch(o => o.part1) // should return TPart
(also on ts-playground)
Deleting the first overload allows to compile but the return types are wrong. What am I missing?