0

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?

1 Answer 1

1

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 {
  // ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.