'error TS2532: Object is possibly 'undefined' on sort
Could anybody holp me? I have following situation:
I'm initalize variable like this:
let tableData: ShootingRange[] = [];
The I fill tableData:
this.shootingRngeService.GetShootingRanges()
.subscribe({
next: ((value: any) => {
tableData = value;
this.dataSource.data = tableData;
}),
error: ((value: any) => {
})
}
)
then I wish to sort it like this:
CustomSort(field: string){
const myproperty = 'Name' as const;
if(tableData != undefined){
let sorted = tableData.sort((a,b) => {
if (b[myproperty] < a[myproperty] ) return 1;
if (b[myproperty] > a[myproperty] ) return -1;
return 0;
});
for(let i = 0; i < sorted.length; i++){
console.log(tableData[i])
}
}
}
But I have following error: Error: app/components/shootingRange/shooting-range-list/shooting-range-list.component.ts:119:27 - error TS2532: Object is possibly 'undefined'.
119 if (b[myproperty] > a[myproperty] ) return -1;
Anybody have an idea what is wrong? If I use hard coded sample array this sorting works fine....
Solution 1:[1]
This is very hard to answer without seeing the ShootingRange interface.
I'm guessing it's either that the Name field of that interface is optional. So TypeScript can't guarantee that the value is set.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jonas |
