typescript - 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
.
解决方案
AFAIK,如果不手动转换为{[K in CarId]: number}
,打字稿无法检测到cars.reduce((acc, car, i) => ({ ...acc, [car.id]: i }), {})
(或其他方式)将返回一个以整个 CardId 作为索引的对象。
推荐阅读
- sql-server - 在相邻窗口中自动打开新查询
- vba - 自动化图表的季度更新
- python - 用减号解析字符串,保留减号
- r - GLM 中缺少结果以及如何找到 f 值
- sorting - QtSpim 中的排序/交换方法返回未知错误
- python - 无法更改音频文件格式 - python
- .net - 将行为添加到端点行为后未执行 IEndpointBehavior ApplyClientBehavior 方法
- php - 如何在 Laravel 中链接 2 个单独的模型?
- web-crawler - 在 StormCrawler 中不跟踪 url.path 有什么影响?
- android - 不建议使用底部导航的活动吗