将已区分的并集(或对象类型数组)转换为以文字属性为键的映射类型

时间:2018-12-01 18:56:41

标签: typescript

我可以将Array<A | B> 类型转换为{ [key: (A | B)['type']]: A | B },其中类型"a"映射为类型A,类型"b"映射键入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 }

我想避免显式声明ByKind对象类型的每个键,因为它们已经在类型AB中声明了。

1 个答案:

答案 0 :(得分:3)

您非常接近,我们可以使用映射类型来映射Kind[type]中的字符串文字的并集,但是然后我们需要使用Extract条件类型从并集中提取类型适合钥匙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 }>
}