我收到如下錯誤
Argument of type 'any' is not assignable to parameter of type 'never'.
錯誤在alarm[key]
這是我的代碼:
import { Injectable } from '@angular/core';
import alarmData from '../../mockData/alarmdData.json';
interface IAlarm {
createdTime: string;
station: string;
deviceID: string;
category: string;
alarmValue: number;
alarmType: string;
status: string;
startTime: string;
endTime: string;
handleState: string;
}
@Injectable({
providedIn: 'root',
})
export class AlarmDataService {
setColumnData(key: string, array: number[] | string[]): void {
alarmData.forEach((alarm: IAlarm) => array.push(alarm[key]));
}
logData() {
console.log(alarmData);
}
}
My json file content is below:
[
{
"createdTime": "2022/03/24 18:00",
"station": "testStation",
"deviceID": "S1001",
"category": "SO2",
"alarmValue": 33,
"alarmType": "SO2 limit",
"status": "alarm",
"startTime": "2022/03/24 18:00",
"endTime": "2022/03/24 19:00",
"handleState": "handled"
},
{
"createdTime": "2022/03/24 19:00",
"station": "test1Station",
"deviceID": "S1002",
"category": "NO",
"alarmValue": 33,
"alarmType": "NO limit",
"status": "alarm",
"startTime": "2022/03/24 20:00",
"endTime": "2022/03/24 21:00",
"handleState": "handled"
}
]
Why I get this hint 'Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IAlarm'. No index signature with a parameter of type 'string' was found on type 'IAlarm'.'.
What should I do to debug my code? Thank you for helping me in advance.
I have tried to change the array to 'any' but it still does not work.
uj5u.com熱心網友回復:
我閱讀您的代碼的方式,該函式的意圖似乎setColumnData如下:
給定
IAlarm介面上定義的屬性和物件陣列,IAlarm從每個物件中提取該屬性的值,并將所有這些值放入單個陣列中。
考慮到這一點,這應該有效:
setColumnData<Key extends keyof IAlarm>(key: Key, array: IAlarm[Key][]): void {
alarmData.forEach((alarm) => array.push(alarm[key]));
}
一些注意事項:
- 通過使用
Key extends keyof IAlarm,我們確保key引數只能是IAlarm(例如station或category)的屬性之一。任何其他值都會導致型別錯誤。 - 使用
IAlarm[Key][]作為array引數的型別可確保陣列中值的型別與 on 屬性的型別相匹配IAlarm(numberforalarmValue,string對于其他任何東西)。這樣做的好處是無需修改此方法即可支持其他型別(例如,如果您要向 中添加boolean屬性IAlarm)。
這是TS Playground 上的簡化版本。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/449562.html
標籤:typescript
