简体   繁体   中英

Convert discriminated union (or array of object types) into a mapped type with a literal property as the key

Can I convert an Array<A | B> Array<A | B> type into { [key: (A | B)['type']]: A | B } { [key: (A | B)['type']]: A | B } where type "a" maps to type A , and type "b" maps to type B .

type A = {type: 'a'}
type B = {type: 'b'}

type Kinds = [A, B]
type Kind = Kinds[number]

// How to use the above types to get this?
type ByKind = { a: A, b: B }

I want to avoid explicitly declaring each key of the ByKind object type, since they are already declared within types A and B .

You were pretty close, we can use a mapped type to map over the union of string literals in Kind[type] but we then need to use the Extract conditional type to extract the type from the union that fits the key P

type A = {type: 'a'}
type B = {type: 'b'}

type Kinds = [A, B]
type Kind = Kinds[number]

type ByKind = {
    [P in Kind['type']]: Extract<Kind, { type: P }>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM