Search code examples
typescriptdiscriminated-union

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.


Solution

  • 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 }