angularkendo-gridng-templatetypesafe

how to make angular kendo-grid typesafe


Variable dataItem has type any, I guess the type can't be inferred from the [kendoGridBinding] which binds to Array<T>? Do I need to use a type guard or type assertion on each column?

<kendo-grid [kendoGridBinding]="processTable()">
    <kendo-grid-column 
       field="qty"  <-- not type safe
       title="Qty Required"> 
    </kendo-grid-column>
    <kendo-grid-column title="Processed">
      <ng-template kendoGridCellTemplate let-dataItem>
        {{ dataItem.events.length }}  <--- not type safe
      </ng-template>
    </kendo-grid-column>
   ...

I have a growing number of tables and refactoring the code e.g. renaming variables could in this situation cause errors undetected by the compiler.


Solution

  • Your issue can be solved by wrapping the let-dataItem:

    Instead of this:

    <kendo-grid-column title="Processed">
      <ng-template kendoGridCellTemplate let-dataItem>
        {{ dataItem.events.length }}  <--- not type safe
      </ng-template>
    </kendo-grid-column>
    

    Do this:

    <kendo-grid-column title="Processed">
      <ng-template kendoGridCellTemplate let-untypedDataItem>
        <ng-container *ngIf="identity(untypedDataItem) as dataItem">
            {{ dataItem.events.length }}  <--- Now is type safe
        </ng-container>
      </ng-template>
    </kendo-grid-column>
    
    // typescript
    identity(foo: any): MyType {
        return foo;
    }
    
    NEWEST SYNTAX:
    <ng-template #foo let-untypedDataItem>
        @if (identity(untypedDataItem); as dataItem) {
            {{ dataItem.events.length }}  <--- Now is type safe
        }
    </ng-template>
    

    This is more or less the same answer I gave here, you can check other people approaches there.


    The type assertion is noticed by the IDE when *ngFor or *ngIf is in use. The downside with this solution is that the inner is rendered "later" because of the *ngIf. And also, ngZone is called at every lifecycle which might result in a little performance drawback.