Typescript check type against enum

Viewed 31

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,
   }
}
1 Answers

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

Related