typescript - 返回类型中数组中的keyof是什么意思?
问题描述
我在一位同事的源代码中发现了这个 TypeScript 结构:
protected getData(): { [item in keyof Fruit]: any; } {
return {
color: [],
tree: [],
};
}
我不明白签名中的返回类型定义:{ [item in keyof Fruit]: any; }
这是什么意思?
解决方案
getData
返回一个对象。如果我们假设该对象中有一个名为item
then的键item
必须是in
type keyof Fruit
。如果该类型Fruit
定义了不同的键,则该类型keyof Fruit
是每个键的联合类型。
此返回类型的定义方式使用索引签名类型
例如:
interface Fruit {
color: string;
tree: string;
}
type FruitKeys = keyof Fruit; // 'color'|'tree'
type Return = {
// item is either 'color' or 'tree'
[item in FruitKeys]: any; // This is an index signature defining how this type can be indexed.
}
const a : Return = {
color: 'aaa',
tree: null,
abc: '' // error abc not in the keys of Fruit
}
定义它的更短的方法是使用实用Record
程序类型。在这种情况下,写起来更短:
function getData(): Record<keyof Fruit, any> {
return {
color: [],
tree: [],
};
}
推荐阅读
- python - 用 Python 编写 Discord 机器人 - 我有多个 client.events,但一次只有一个有效
- php - 我有一个 if 语句,但我有问题
- python - discord py - 如果用户收到新排名,则发送消息(on_member_update)
- amazon-web-services - 将未知大小的实例类型和权重容量列表添加到 AWS CF 模板 (YAML) 中的 Auto Scaling 组
- python - 单个网站仅通过 VPN 拒绝 selenium
- r - 根据早期的目标参数将三个变量之一映射到目标?
- php - PHP - 写入文件根本不会输出任何内容,路径确实存在
- cnc - 发那科适配器问题
- python - Django test cases - data not getting loaded into default database
- python - How to pass color as a function parameter in python