const cars = [
{ id: 'id1', name: 'ford' },
{ id: 'id2', name: 'audi' },
{ id: 'id3', name: 'bmw' },
] as const;
type CarId = typeof cars[number]['id'];
const carIndexes = cars.reduce((acc, car, i) => ({ ...acc, [car.id]: i }), {});
console.log(carIndexes);
This code works fine, and prints out
{ id1: 0, id2: 1, id3: 2 }
carIndexes gives me a map that allows me to look up the index of each car by their id, but I would like carIndexes to be strongly typed. When I change its type signature to { [K in CarId]: number }:
const carIndexes: { [K in CarId]: number } = cars.reduce((acc, car, i) => ({ ...acc, [car.id]: i }), {});
I get the error:
error TS2739: Type '{}' is missing the following properties from type '{ id1: number; id2: number; id3: number; }': id1, id2, id3
I would like to use a plain object, rather than a Map, because an object with type { [K in CarId]: number } guarantees that looking up the index can't fail for any CarId.