Agata
Agata

Reputation: 362

Cannot convert undefined or null to object typescript

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);
  }
}

Upvotes: 1

Views: 1335

Answers (2)

a.mola
a.mola

Reputation: 4011

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 ?? {});
...

Upvotes: 4

OctavianM
OctavianM

Reputation: 4597

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);
  }
}

Upvotes: 1

Related Questions