首页 > 解决方案 > Typescript 将 const 对象数组转换为类型化索引查找对象

问题描述

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);

此代码工作正常,并打印出来

{ id1: 0, id2: 1, id3: 2 }

carIndexes给了我一张地图,让我可以通过它们查找每辆车的索引id,但我想carIndexes被强类型化。当我将其类型签名更改为{ [K in CarId]: number }

const carIndexes: { [K in CarId]: number } = cars.reduce((acc, car, i) => ({ ...acc, [car.id]: i }), {});

我得到错误:

error TS2739: Type '{}' is missing the following properties from type '{ id1: number; id2: number; id3: number; }': id1, id2, id3

我想使用普通对象,而不是Map,因为具有类型的对象{ [K in CarId]: number }保证查找索引不会因任何CarId.

标签: typescript

解决方案


AFAIK,如果不手动转换为{[K in CarId]: number},打字稿无法检测到cars.reduce((acc, car, i) => ({ ...acc, [car.id]: i }), {})(或其他方式)将返回一个以整个 CardId 作为索引的对象。


推荐阅读