-2

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....

Zantor
  • 1
  • 1
  • It means what it says, `b[myproperty]` or `a[myproperty]` may be undefined. You can't use `undefined` as one side of a `>` or `<` comparison. So check if one or both of them is undefined before comparing, or substitute a suitable default value (e.g. `if ((b[myproperty] ?? 0) < (a[myproperty] ?? 0)) return 1;`) or, assert that there will always be a value (`if (b[myproperty]! < a[myproperty]!) return 1;`). – Heretic Monkey Feb 21 '22 at 23:41
  • Does this answer your question? [How can I solve the error 'TS2532: Object is possibly 'undefined'?](https://stackoverflow.com/questions/54884488/how-can-i-solve-the-error-ts2532-object-is-possibly-undefined) – Heretic Monkey Feb 21 '22 at 23:42

1 Answers1

0

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.

Jonas
  • 1