2

这就是我要的

type Report = {
  branches: number; // should be required
  functions: number; // should be required
  lines: number; // should be required
  statements: number; // should be required
};

const report: Report = {
  branches: 10,
  functions: 19,
  lines: 54,
  statements: 67,
}

但我不能这样做

const items = Object.keys(report).map(key => report[key])

打字稿(版本 4.3.5)显示以下错误report[key]

元素隐含地具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“报告”。在“报告”类型上找不到具有“字符串”类型参数的索引签名.ts(7053)

所以我试试这个

export type Report = {
  [key: string]: number;
  branches: number;
  functions: number;
  lines: number;
  statements: number;
};

但现在它允许类似

const withFoo: Report = {
  branches: 25.3,
  imABug: 45, // should not be allowed!
  functions: 20.1,
  lines: 70.01, 
  statements: 45,
},
4

1 回答 1

2

那是因为您正在创建一个字符串数组Object.keys()并尝试映射到Report对象,我觉得这只是不好的实现。

你为什么不试试这个来迭代属性:

type Report = {
  branches: number; // should be required
  functions: number; // should be required
  lines: number; // should be required
  statements: number; // should be required
};

const foo: Report = {
  branches: 10,
  functions: 19,
  lines: 54,
  statements: 67,
}


Object.entries(foo).map(([key, value]) => console.log(key, value));
于 2021-09-01T14:31:38.090 回答