[英]Extract specific union item given generic param in typescript
給定 typescript 個對象的並集,我想提取一個特定的並集項。
這將幫助我動態鍵入 function,其中特定id
作為參數傳遞。
這是我想要實現的示例:
type A = {
id: 'a',
search: {
a: number
}
}
type B = {
id: 'b',
search: {
b: string
}
}
type MyUnion = A | B
type GetFromUnion<T extends MyUnion['id']> = // complete the implementation
/**
* I expect type C to be equal to:
*
* type C = {
* id: 'b',
* search: {
* b: string
* }
* }
*/
type C = GetFromUnion<'b'>
我嘗試過但不起作用的方法:
// Always return never
type GetFromUnion<T extends MyUnion['id']> = MyUnion['id'] extends T ? MyUnion : never
Extract
來拯救:
type GetFromUnion<T extends MyUnion['id']> = Extract<MyUnion, {id : T}>
Extract
的實現是:
type Extract<T, U> = T extends U ? T : never;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.