Home > Net >  TS2322: Type 'Date | undefined' is not assignable to type 'Date' even though I c
TS2322: Type 'Date | undefined' is not assignable to type 'Date' even though I c

Time:12-15

Here is what I have so far:

I have one Array of Dates: trackedElementsTimestamps: Date[]; and one Array of Objects: trackedElements: TrackingEvent[];

In TrackingEvent there is a Date: timestamp?: Date;

My goal is to get every timestamp out of trackedElements and push it into trackedElementsTimestamps:

for (let i = 0; i < this.trackedElements.length; i  ) {
   if (this.trackedElements[i].timestamp != undefined) {
      this.trackedElementsTimestamps[i] = this.trackedElements[i].timestamp;
   } else {
      console.log("trackedElements["   i   "].timestamp is undefined")
   }
}

At this.trackedElementsTimestamps[i] it throws following error:

TS2322: Type 'Date | undefined' is not assignable to type 'Date'. Type 'undefined' is not assignable to type 'Date'.

Also I don't want to use ! because it can produce a problem later on in my code. What's another way to solve this?

CodePudding user response:

Two options come to mind:

Cast it as Date.

this.trackedElementsTimestamps[i] = this.trackedElements[i].timestamp as Date;

Or assign the current loop item to a local variable

for (let i = 0; i < this.trackedElements.length; i  ) {
   const currItem = this.trackedElements[i]; 

   if (currItem.timestamp != undefined) {
      this.trackedElementsTimestamps[i] = currItem.timestamp;
   } else {
      console.log("trackedElements["   i   "].timestamp is undefined")
   }
}

cheers

CodePudding user response:

Your best shot is using a .forEach or a .map rather than a classical for loop. TypeScript has some issues when iterating using a classic loop for reasons that I am not qualified enough to explain.

trackedElements.forEach(element => {
    if (element.timestamp) {
        trackedElementsTimestamps.push(element.timestamp);
    }
})
  • Related