Type checking Angular template

928 Views Asked by At

I would like to use type checking on angular templates.

When a property has 2 or more possible types, the template is not able to determine which is the current type in its context. Even using an "if" to check for the presence of the property, my IDE (VSCODE) isn't happy. With typescript side I could just use if ('property' in myObj) but I can't reproduce this on the template side.

Example: https://stackblitz.com/edit/angular-ivy-bjfyu9?file=src/app/app.component.html

Just remove the FOO interface on the property, then it work...

How can I check the type of a property in an angular template?

I read https://angular.io/guide/template-typecheck but nothing about a case when a property has 2 or more types possibles (except null).

I know it could work if I add a property like "kind" for union in each object. But I can't change the data schema.

Using angular 14

  "angularCompilerOptions": {
    "strictTemplates": true,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true
  }
1

There are 1 best solutions below

0
AT82 On

If you cannot do anything to the data schema, the last resort would be to use any in the template. Not anything I would ever recommend in any other situation, unless really neccessary, but if there is no other way, then do that:

<div *ngIf="$any(property).date">{{ $any(property).date }}</div>

Your forked STACKBLITZ