I have a task where a function is needed to return the correct type based on a key-type mapping it has access to.
Here's a simplified example of what I'm working on. Almost there, but seems like something is missing.
Note: This is intended for a library and user-provided types are unknown.
type Plane = {
name: string;
wings: number;
};
type Car = {
name: string;
wheels: number;
};
type Vehicles = {
cars: Car;
planes: Plane;
};
type TypeMap = { [key: string]: any };
type Mapper<VehicleMapType extends TypeMap = TypeMap> = {
getVehicle<
VehicleType extends
| Extract<keyof VehicleMapType, string>
| never = Extract<keyof VehicleMapType, string>
>(
type: VehicleType
): VehicleMapType[VehicleType];
};
const mapper: Mapper<Vehicles> = null;
const vehicle1 = mapper.getVehicle('cars');
// This outputs a Car!
console.log(vehicle1);
const getVehicles = <
VehicleMapType extends TypeMap = TypeMap,
VehicleType extends Extract<keyof VehicleMapType, string> | never = Extract<
keyof VehicleMapType,
string
>
>(
type: VehicleType
): VehicleMapType[VehicleType] => {
return null;
};
const vehicle2 = getVehicles<Vehicles>('cars');
// Need help to get just a Car instead of a Car or a Plane?
console.log(vehicle2);
Thanks!
Edit
In addition to that, we're encountering an issue with the Mapper implementation as evident from this TS Playground