Return 基于可选泛型参数的类型

Return type based on optional generic argument

我无法将 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-playground 上)

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

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

您必须为返回的那个添加重载 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
}

Updated playground

部分内容如下:

// 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
}