基于可选泛型参数的返回类型



我无法将SO上的许多函数重载示例转移到我的用例:

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

(也在ts操场上(

删除第一个重载允许编译,但返回类型错误。我错过了什么?

实现不是函数的公共签名之一,因此只显示了第一个重载。

您必须为返回TPart:的一个添加过载

function fetch(): T;
function fetch<TPart>(selector?: (obj: T) => TPart): TPart; // <====
function fetch<TPart>(selector?: (obj: T) => TPart) {
if (selector)
return selector(value)
return value
}

更新的操场

其中的部件如下:

// First overload signature (part of the public type of the function):
function fetch(): T;
// Second overload signature (also part of the public type of the function):
function fetch<TPart>(selector?: (obj: T) => TPart): TPart;
// Implementation (NOT part of the public type of the function):
function fetch<TPart>(selector?: (obj: T) => TPart) {
if (selector)
return selector(value)
return value
}

最新更新