Search code examples
javascriptangular13typeguardstypescript4.0

Typescript 4.4.3 : How to pass string as key and extract its value(list)


I have a list of array something like this:

//model.ts
export class Item{
    name: string;
    age: string;
    Id: number;
}

export class TempArray{ 
  [key : string] : PubMedDetails[];
}

//component.ts

listOfItems: Item[] = []
listOfTempArray: TempArray[] = [];

listOfTempArray ={
'class2':{'name': 'abc', 'age': 'ten', 'Id': 3398},
'class3':{'name': 'Radha','age': 'two', 'Id': 9876},
'class4':{'name': 'hjgf', 'age': 'five', 'Id': 8766}
}

 FetchData() {
    let che: keyof TempArray = 'Radha' //I will be receiving this value from UI as ngModel
    //trying to assign Radha's details to listOfItems
    this.listOfItems = this.listOfTempArray[che] //line 4

    this.listOfItems.forEach(x => {
      if (this.listOfDiseaseNames.indexOf(x.names.toLowerCase()) == -1) { //line 7
        this.listOfDiseaseNames.push(x.names.toLowerCase())   //line 8
      }
    })
  }
tempArray = {
'class2':{'name': 'abc', 'age': 'ten', 'Id': 3398},
'class3':{'name': 'gg', 'age': 'two', 'Id': 9876},
'class4':{'name': 'hjgf', 'age': 'five', 'Id': 8766}
}

in Typescript v4.4 (angular 13) how do I get the values of class4 by passing 'class4'(string) as key

Errors I am getting: in line 4 :Element implicitly has an 'any' type because index expression is not of type 'number'. in line 7 and 8 : Argument of type 'string' is not assignable to parameter of type 'never'


Solution

  • Here you initialize listOfTempArray as array of TempArray:

    listOfTempArray: TempArray[] = [];
    

    But later you refer to it as it was of type TempArray, not TempArray[]

    FetchData() {
        let che: keyof TempArray = 'Radha' //I will be receiving this value from UI as ngModel
        //trying to assign Radha's details to listOfItems
        this.listOfItems = this.listOfTempArray[che] // here should be either this.listOfTempArray[index][che] for TempArray[] type OR this.listOfTempArray[che], but with TempArray type
    
        this.listOfItems.forEach(x => {
          if (this.listOfDiseaseNames.indexOf(x.names.toLowerCase()) == -1) { //line 7
            this.listOfDiseaseNames.push(x.names.toLowerCase())   //line 8
          }
        })
      }
    

    Line 7 and 8 errors should disappear when you resolve line 4 error.