Home > other >  Angular - Got type mismatch error while using for-in loop
Angular - Got type mismatch error while using for-in loop

Time:01-08

After selecting a particular date on the DOM calendar, I want to display if the date is Sunday or not. So I implement the logic something like this :

SunValue = [
  {sunUn : false},
  {sunUn2 : false}
]

sunday(){

  let dt = new Date(_moment(this.Model.unloadingDate.value).format("YYYY-MM-DD").toString())
  let dt2 = new Date(_moment(this.Model.receiptDate.value).format("YYYY-MM-DD").toString())

  let dayobj = {
    day1: dt.getDay(),
    day2: dt2.getDay()
  }
  for(const key in dayobj){
    if(dayobj[key] == 0){
      //some logic here
    }
  }
}

But in the for-in loop it says:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ day1: number; day2: number; }'. No index signature with a parameter of type 'string' was found on type '{ day1: number; day2: number; }' const key: string

and I cant use the type annotation here. Does anyone know how to fix this?

CodePudding user response:

Solution 1: Cast obj as any type

if ((dayobj as any)[key] == 0) {
  //some logic here
}

Solution 2: Define type for dayObj

let dayobj: {[key:string]: number} = {
  day1: dt.getDay(),
  day2: dt2.getDay(),
};

Sample Solutions on StackBlitz

  •  Tags:  
  • Related