[英]Type for intersection of all return types with list of functions
假設我有一個像這樣的函數數組:
const foo: Array< () => object > = [
() => ({ one: 'fish' }),
() => ({ two: 'fish' }),
() => ({ red: 'fish' }),
() => ({ blue: 'fish' })
]
是否可以編寫一種類型來交叉所有這些函數的返回類型?
{
one: string,
two: string,
red: string,
blue: string,
}
基本上,如果您將所有這些函數減少到一個結果中會產生什么結果的類型。
有趣的問題。 這可以使用映射類型和條件類型的組合來完成; 我們需要:
Array<() => object>
這樣數組的實際內容就可以用來構造類型了,{one: string} | {two: string} | {red: string} | {blue: string}
這樣的聯合{one: string} | {two: string} | {red: string} | {blue: string}
{one: string} | {two: string} | {red: string} | {blue: string}
{one: string} | {two: string} | {red: string} | {blue: string}
所以我們需要能夠獲取屬性名稱( keyof
不適用於這樣的聯合),這是一個實現:
const foo = [
() => ({ one: 'fish' }),
() => ({ two: 'fish' }),
() => ({ red: 'fish' }),
() => ({ blue: 'fish' })
];
type ComponentType<A extends any[]> = A extends (infer U)[] ? U : never
type ReturnsUnion = ReturnType<ComponentType<typeof foo>>
// {one: string} | {two: string} | {red: string} | {blue: string}
type KeyOfUnion<T> = T extends infer U ? keyof U : never
// KeyOfUnion<ReturnsUnion> = 'one' | 'two' | 'red' | 'blue'
type ValueInUnion<T, K extends PropertyKey> = T extends { [k in K]: infer V } ? V : never
type Result = { [K in KeyOfUnion<ReturnsUnion>]: ValueInUnion<ReturnsUnion, K> }
// { one: string, two: string, red: string, blue: string }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.