我已经使用 Typescript 几个月了,但一直坚持让我的索引签名正常工作。
sensorTestData = [
{
altitude: 249.74905877223617
gas: 4361
humidity: 53.16487239957308
pressure: 30.100467823211194
temperature: 69.0322421875
timestamp: "2022-02-23 00:10:12.377165"
},
{
altitude: 249.5376138919663
gas: 700
humidity: 53.15552212315537
pressure: 30.100694114206632
temperature: 69.07759374999999
timestamp: "2022-02-23 00:10:13.574070"
}
]
对象数组如下所示:{ temperature: number; humidity: number; pressure: number; altitude: number; gas: number; timestamp: string; }
我尝试了多种不同的方法来添加 [metric: string]: any 并且如果不使用“any”似乎无法到达任何地方。
这是我在对象数组中使用的函数示例:
const getMax = (metric: string) => {
return parseFloat(
Math.max(...sensorTestData.map((obj: {
temperature: number;
humidity: number;
pressure: number;
altitude: number;
gas: number;
timestamp: string;
}) => obj[metric])).toFixed(2)
);
};
console.log("maxTemp", getMax("temperature"));
console.log("maxHumidity", getMax("humidity"));```
Error thrown: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ temperature: number; humidity: number; pressure: number; altitude: number; gas: number; timestamp: string; }'.
No index signature with a parameter of type 'string' was found on type '{ temperature: number; humidity: number; pressure: number; altitude: number; gas: number; timestamp: string; }'.ts(7053)