这就是我要的
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,
},