Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate each member of a union type

I have a generated union type that looks something like:

type Result = { type: 'car' } | { type: 'boat' }

How can I separate them so that I can create an individual type for each of these? eg:

type BoatResult = { type: 'boat' }
type CarResult = { type: 'card' }

Where they have to be created from the original Result type.

like image 883
sindre Avatar asked Oct 31 '25 00:10

sindre


1 Answers

You can use the Extract conditional type to Extract to get a type out of a union that extends a given type. If your union is actually as simple as in the question it does not make much sense, but if you have extra fields you can use this to extract the full type from the union.

type Result = { type: 'car', a: number } | { type: 'boat', b: string }

type Car = Extract<Result, { type: 'car' }> //{ type: 'car', a: number }
type Boat = Extract<Result, { type: 'boat'} > // { type: 'boat', b: string }
like image 97
Titian Cernicova-Dragomir Avatar answered Nov 01 '25 17:11

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!