Issue
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?
Solution
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
Answered By - akotech
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.