Home > Software engineering >  Method parameters matching enum value in TypeScript
Method parameters matching enum value in TypeScript

Time:03-10

I want to create a type match when calling a method with enum values.

Imagine the next example:

enum Vehicle {
  Car,
  Bus,
  Plane
};

type CarParams = { carId: string };
type BusParams = { busId: string };
type PlaneParams = { planeId: string };

const TypeMap = {
  [Vehicle.Car]: CarParams,
  [Vehicle.Bus]: BusParams,
  [Vehicle.Plane]: PlaneParams,
};

function showDriver(vehicle: Vehicle, params: TypeMap[valueof vehicle]): void {
  // ...
}

I can't really do this: TypeMap[valueof vehicle] But I want to help whoever uses my method to understand the parameters they need to send, so that calls look like this:

showDriver(Vehicle.Bus, { busI...

This would automatically autocomplete to busId and expect a string.

How do I do that?

CodePudding user response:

This is how you can achive:

enum Vehicle {
    Car,
    Bus,
    Plane,
}

interface CarParams {
    carId: string;
}

interface BusParams {
    busId: string;
}

interface PlaneParams {
    planeId: string;
}

type Params = {
    [Vehicle.Bus]: BusParams;
    [Vehicle.Car]: CarParams;
    [Vehicle.Plane]: PlaneParams;
};

function showDriver<T extends Vehicle>(vehicle: T, params: Params[T] ): void {
  // ...
}
  • Related