我無法將 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 上)
洗掉第一個多載允許編譯,但回傳型別錯誤。我錯過了什么?
uj5u.com熱心網友回復:
該實作不是該函式的公共簽名之一,因此只顯示了第一個多載。
您必須為回傳的添加多載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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/405255.html
標籤:
