Search code examples
angularangular-pipe

Using async pipe looses reference to object type


I have a simple problem. When I'm using async pipe in template IDE don't know what type has the object from the async pipe.

Here is a short example:

  <ng-container *ngIf="(state$ | async).foo as foo">

Actually foo is of type Foo: {id:string, name:string, value: number}

The problem is, when I want to use foo in template IDE don't know that foo has id, or name, or value.

Is there any clean solution to "cast" foo to Foo?


Solution

  • as foo statement is create a template variable not for casting ,if you use like this

       <ng-container *ngIf="(state$ | async).foo.id">
    

    you will get type intellisense but when you create a template variable this information seem to be lost.

    this consider a bug and may be solve in future.

    <ng-container *ngIf="($state | async) as foo">
        {{foo | json}}
        <div>
            {{foo.id}} <!-- foo has no type information-->
        </div>
    
      {{value.name}} <!-- declared property has type information-->
    </ng-container>
    

    stackblitz demo