javascriptangulartypescriptdictionarydate-pipe

How to use date-pipe inside for loop in angular?


I want to use date-pipe for the values of my dictionary. So I tried this.

<div *ngFor="let field of watchlist | keyvalue">
<li *ngIf="field.value  && field.key">{{field.key}}: {{field.value | date:'d MMM y'}}

but got an error

    Error: src/app/update-watchlist/update-watchlist.component.html:45:76 - error TS2769: No overload matches this call.
  Overload 1 of 3, '(value: string | number | Date, format?: string | undefined, timezone?: string | undefined, locale?: string | undefined):
string | null', gave the following error.
    Argument of type 'unknown' is not assignable to parameter of type 'string | number | Date'.
      Type 'unknown' is not assignable to type 'Date'.
  Overload 2 of 3, '(value: null | undefined, format?: string | undefined, timezone?: string | undefined, locale?: string | undefined): null', gave the following error.
    Argument of type 'unknown' is not assignable to parameter of type 'null | undefined'.
      Type 'unknown' is not assignable to type 'null'.
  Overload 3 of 3, '(value: string | number | Date | null | undefined, format?: string | undefined, timezone?: string | undefined, locale?: string | undefined): string | null', gave the following error.
    Argument of type 'unknown' is not assignable to parameter of type 'string | number | Date | null | undefined'.
      Type 'unknown' is not assignable to type 'Date'.

45                     <li *ngIf="field.value  && field.key">{{field.key}}: {{field.value | date:'d MMM y'}}

Solution

  • Make sure field.value is a string or a number or a Date. It currently is seen as unknown.

    To do that, you'll either have to better type watchlist or explicitly field.value.