Home > Software engineering >  How to set type of field for async pipe inside an angular-template?
How to set type of field for async pipe inside an angular-template?

Time:09-03

I have the following statement in my template in my table

<span>
{{ row[columns[1].field] | async | beautifyMyString}}
</span>

Where as beautifyMyString accepts string | number | undefiend.

row[columns[1].field] on the other hand should be an Observable<string>. However, angular state out, that the async pipe will return Observable<unknown>. I guess this is because its not clear what the generic field is containing. But even if Im doing something like this:

    {{ asStringObservable(row[columns[1].field]) | async | beautifyMyString}}

where as

    asStringObservable(observable: any): Observable<string> {
        return observable as Observable<string>;
    }

Angular prints

Argument of type 'string | null' is not assignable to parameter of type 'string | number | undefined'.

I guess, I have to narrow the field-content before pass its content to the async pipe.

How can I do that?

CodePudding user response:

1st step: make your pipe accept null, because async pipe can return null sometimes when there is no value yet.

2nd: your colums should contain something more complex than string in a field field

interface Column<T> {
  field: keyof T;
}

and

columns: Column<TableRowModel> = ...

this way typings will be correctly inferred

  • Related