const vehicles = [
{ id: 'id1', name: 'bike' },
{ id: 'id2', name: 'scooter' },
{ id: 'id3', name: 'motorcycle' },
] as const;
type VehicleId = typeof vehicles[number]['id'];
const vehicleIndexes = vehicles.reduce((acc, vehicle, i) => ({ ...acc, [vehicle.id]: i }), {});
console.log(vehicleIndexes);
This piece of code is functioning correctly and displays
{ id1: 0, id2: 1, id3: 2 }
vehicleIndexes
provides a map enabling the retrieval of each vehicle's index by their id
, however, I desire for vehicleIndexes
to be strictly typed. Upon modifying its type definition to { [K in VehicleId]: number }
:
const vehicleIndexes: { [K in VehicleId]: number } = vehicles.reduce((acc, vehicle, i) => ({ ...acc, [vehicle.id]: i }), {});
An error occurs:
error TS2739: Type '{}' is missing the following properties from type '{ id1: number; id2: number; id3: number; }': id1, id2, id3
I prefer using a plain object over a Map
, since an object with the type { [K in VehicleId]: number }
ensures that the search for the index cannot fail for any VehicleId
.