Home > OS >  Cannot convert undefined or null to object typescript
Cannot convert undefined or null to object typescript

Time:10-08

I wrote a pipe but when I using the pipe gives an error

HTML

<mat-tab *ngFor="let officer of companies?.officers | valueArray" label="{{officer.name}}">

TS

    import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'valueArray',
})
export class ValueArrayPipe implements PipeTransform {
  transform(objects: any = []): any {
    return Object?.values(objects);
  }
}

CodePudding user response:

Use the null-coalescing (??) operator to use a default value if is null or undefined.

Setting a default value for a function argument only works when nothing is passed for that argument into the function, so that should be why your default [] value doesn't work.

...
  transform(objects: any = []): any {
    return Object.values(objects ?? {});
...

CodePudding user response:

Try accounting for the fact that the input parameter for the transform method can also be null or undefined:

@Pipe({
  name: 'valueArray',
})
export class ValueArrayPipe implements PipeTransform {
  transform(objects: any = []): any {
    if (!objects) {
      return null; // or [], or undefined
    }
    return Object.values(objects);
  }
}
  • Related