简体   繁体   中英

Extend Discriminated Unions

is it possible to do transform this DU using mappend/conditional types

type MyDU =
| {kind: 'foo'}
| {kind: 'bar'}

type Transformed = DUTransformer<MyDU>

such that we get the folllowing result

type Transformed =
| {kind: 'foo', foo: boolean}
| {kind: 'bar', bar: boolean}

Yes, because TypeScript will distribute mapped types over a union :

type MyDU =
| {kind: 'foo'}
| {kind: 'bar'}

type Kinded<T extends string> = { kind: T }

type DUTransformer<T> = T extends Kinded<infer K> ? T & {[K1 in K]: boolean} : never

type Transformed = DUTransformer<MyDU>

The type of Transformed is:

type Transformed = ({
    kind: 'foo';
} & {
    foo: boolean;
}) | ({
    kind: 'bar';
} & {
    bar: boolean;
})

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