How do I accept any type that has string property values?

Discussão em 'Angular' iniciado por Russell M, Agosto 29, 2025.

  1. Russell M

    Russell M Guest

    How can I make this generic typing work?

    interface MyRowItem {
    source: string;
    name: string;
    email: string;
    }
    const rowItem: MyRowItem = {
    source: 'EXAMPLE',
    name: 'Example Item',
    email: '',
    };
    interface GenericRowItem { [key: string]: string }
    const genericRowItem: GenericRowItem = rowItem;


    I get this error:

    TS 2322: Type MyRowItem is not assignable to type GenericRowItem.


    In my actual business case, genericRowItem is an Angular @Input(). I want to constrain clients who use this component so that they can't provide objects with non-string properties as input.

    My angular component declares a generic for the input type, like this:

    export class MyComponent<T extends GenericRowItem> {
    @Input() rowData: T[];
    }


    I have tried a bunch of different variations on the GenericRowItem declaration, such as using Record<string, string>, Partial<Record<string, string>> and so on.

    I am specifically looking for a solution in which the MyRowItem interface does not need to be changed.

    I could not figure out how to use either of the solutions described here here (https://stackoverflow.com/a/51237784/22758918), because the assignment is being performed by third-party code (the Angular @Input() binding).

    The component accepting the input may use generics, if that helps:

    class MyComponent<T extends {[key: string]: string}> {
    @Input() rowData: T[];
    }

    <my-component [rowData]="[rowItem]"></my-component> <!-- <-- this doesn't compile -->

    Continue reading...

Compartilhe esta Página