简体   繁体   English

合并 typescript 中的条件映射类型

[英]Merge conditional mapped types in typescript

We specify a type using mapped types using the following base interface我们使用以下基本接口使用映射类型指定类型

interface A {
    a: string
    b: number
    c: number
}

If we index the mapped type with its own keys like this如果我们像这样用自己的键索引映射类型

type B = {
    [K in keyof A]: {
        [K_ in K]: A[K_]
    }
}[keyof A]

It will produce a union of each key with its own type它将生成具有自己类型的每个键的联合

type B = {
    a: string;
} | {
    b: number;
} | {
    c: number;
}

If we use the method above, where we index a mapped type with its own keys, we can extract only some of that keys with their matching type, like in the following example如果我们使用上面的方法,我们用自己的键索引一个映射类型,我们可以只提取一些具有匹配类型的键,如下例所示

type C = {
    [K in keyof A]: A[K] extends number ? {
        [K_ in K]: A[K_]
    } : never
}[keyof A]

Which will produce哪个会产生

type C = {
    b: number;
} | {
    c: number;
}

Question问题

Is it possible to make the same conditional selection we have seen in type C and produce not a union but a full type like the following?是否可以进行我们在type C中看到的相同条件选择,并且生成的不是联合而是完整类型,如下所示?

type C = {
    b: number;
    c: number;
}

Playground Link 游乐场链接

One way to do this is to use key remapping to drop all unmatched keys by remapping them to never :一种方法是使用键重新映射来删除所有不匹配的键,方法是将它们重新映射为never

type C = {
    [K in keyof A as A[K] extends number ? K : never]: A[K]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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