BigLes
BigLes

Reputation: 11

Typescript check type against enum

I have two types, one is enum:

enum Vehicle {
   Car = 'car',
   Plane = 'plane',
}

The second one is regular object, which uses enum as keys:

type VehicleProperties = {
   [Vehicle.Car]: { amountOfWheels: number };
   [Vehicle.Plane]: { amountOfWings: number };
}

How would I do a type VehicleConfig, that unifies both of them and will satisfy:

const vehicle: VehicleConfig = {
   type: Vehicle.Car,
   properties: {
      amountOfWheels: 4,
   }
}

Upvotes: 1

Views: 41

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249556

You could use a custom mapped type:

type VehicleConfig= {
    [P in keyof VehicleProperties]: {
        type: P,
        properties: VehicleProperties[P]
    }
}[keyof VehicleProperties]

const vehicle: VehicleConfig = {
   type: Vehicle.Car,
   properties: {
      amountOfWheels: 4
   }
}

Playground Link

Upvotes: 3

Related Questions