Angular's KeyValuePipe loses its types

Discussão em 'Angular' iniciado por Avraham Weinstein, Janeiro 30, 2025.

  1. When I'm using the Angular's KeyValuePipe in my template, the key pipe-results is losing its type. Here is an example.

    app.component.ts:

    export class AppComponent {
    someObject: Record<`${'key1' | 'key2'}`, {myCustomValue: string}> =
    {key1: {myCustomValue: 'value1'}, key2:{myCustomValue:'value2'}}

    getKeyValueElement(key: 'key1' | 'key2', value: {myCustomValue: string}){
    console.log(key, value)
    }
    }


    Then in my app.component.html:

    <div *ngFor="let keyValueElement of someObject | keyvalue"
    (click)="getKeyValueElement(keyValueElement.key, keyValueElement.value)">
    </div>


    And here is the error I get:

    [​IMG]

    The app refuses to compile since there is incompatibility between the getKeyValueElement key parameter - which is 'key1' | 'key2', and the key from the pipe-result which is string.

    Now, there are 2 different ways that I know how to solve it:

    1. To use $any() in the template to avoid type checking - Not a recommended practice.
    2. To pass a compareFn to the KeyValuePipe with the exact requested types in the signature. this will effect the types rendered in the key&value pipe-results. This is also not a good solution in most cases when you don't really need a custom compareFn.

    So, I'm looking for another solution. In my eyes, this error should not appear in the first place.

    Continue reading...

Compartilhe esta Página