typescript - 在 Typescript 中键入键值对对象并保存对象的键
问题描述
我在以下示例中有键值对对象
interface ItemType {
a: number;
b: string;
}
const list = {
first: {a: 1, b: 'one'},
second: {a: 2, b: 'two'},
third: {a: 3, b: 'three'},
} as { [key in keyof typeof list]: ItemType }
但它会引发错误,例如TS2313: Type parameter 'key' has a circular constraint.
.
我希望所有项目的类型为ItemType
,但仍希望列表保存我插入的键。如果我将其转换为{ [key in string]: ItemType }
,我将丢失列表的键名。:(
解决方案
如果您想验证一个值是否可分配给一个类型,而不是将其扩大到该类型并可能丢弃您关心的信息,您可以使用辅助标识函数,如下所示:
const itemDict = <K extends PropertyKey>(dict: { [P in K]: ItemType }) => dict;
这里itemDict()
应该只接受你正在寻找的类型的对象作为参数:它的键是任何类似键的东西K extends PropertyKey
,当你调用它时编译器会推断它,并且它的属性是ItemType
s。因为键集K
, 是类型的一部分,所以不会被遗忘:
const list = itemDict({
first: { a: 1, b: 'one' },
second: { a: 2, b: 'two' },
third: { a: 3, b: 'three' },
});
list.second.a.toFixed(); // okay
list.fourth; // error!
// Property 'fourth' does not exist on type
// '{ first: ItemType; second: ItemType; third: ItemType; }'
请注意,list
编译器根据需要推断为 type {first: ItemType, second: ItemType, third: ItemType}
。
推荐阅读
- javascript - validate WTForm after selectfield choices updated dynamically with jquery
- jquery - Trumbowyg: Insert text at caret not working
- ffmpeg - How to improve the output video quality with ffmpeg and h264_videotoolbox flag?
- python - For循环没有捕获函数列表中的所有项目
- c# - Dapper stored procedure mapping to complex object
- python - How to run a scheduled task to run a Flask app constantly?
- ios - Twitch 播放器:在从 twitch 播放器播放视频时出现错误 - “哎呀!这个嵌入配置错误”
- javascript - 我的数据没有从反应服务器到达后端节点服务器
- python - 将列表更改为字典 Python
- c# - 根据datagridview中的其他4个给定数量均匀地划分/分离一定数量 - C#