这就是我想要的
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])
typescript(版本4.3.5)显示report[key]
上的以下错误:
元素隐式具有'any'类型,因为'string'类型的表达式不能用于索引'Report'类型。在类型"报告"上找不到带有"字符串"类型参数的索引签名。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,
},
那是因为你正在创建一个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));