首页 > 解决方案 > 返回类型中数组中的keyof是什么意思?

问题描述

我在一位同事的源代码中发现了这个 TypeScript 结构:

protected getData(): { [item in keyof Fruit]: any; } {
    return {
      color: [],
      tree: [],
    };
}

我不明白签名中的返回类型定义:{ [item in keyof Fruit]: any; }

这是什么意思?

标签: typescript

解决方案


getData返回一个对象。如果我们假设该对象中有一个名为itemthen的键item必须是intype 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: [],
    };
}

游乐场链接


推荐阅读