Home > Enterprise >  Merge conditional mapped types in typescript
Merge conditional mapped types in typescript

Time:08-17

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 = {
    b: number;
    c: number;
}

Playground Link

CodePudding user response:

One way to do this is to use key remapping to drop all unmatched keys by remapping them to never:

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