How to use TypeScript generics in an Angular component template?

Discussão em 'Angular' iniciado por Chris Barr, Março 31, 2025.

  1. Chris Barr

    Chris Barr Guest

    I have an Angular component that uses a few generic types. It will set one input based on the type input.

    export interface IEmployee {
    description: string;
    employeeNum: string;
    costCenter: string;
    }

    export interface IEquipment {
    description: string;
    equipmentNum: string;
    }

    @Component({
    selector: 'app-employee-equipment-editor',
    template: `
    <h1>List of {{type}}</h1>
    <ul>
    @for (item of currentList; track $index) {
    <li>
    {{item.description}}
    <br />
    @if(type === 'employees'){
    <span>#{{item.employeeNum}}</span>
    } @else {
    <span>#{{item.equipmentNum}}</span>
    }
    </li>
    }
    </ul>
    `,
    })
    export class EmployeeEquipmentEditorComponent<
    TType = 'employees' | 'equipment',
    TEntity = TType extends 'employee' ? IEmployee : IEquipment
    > {
    @Input({ required: true }) public type!: TType;
    @Input({ required: true }) public currentList!: Array<TEntity>;
    }


    StackBlitz

    Even though both IEmployee and IEquipment have a description property, I get this error in the template:

    Property 'description' does not exist on type 'TEntity'.


    And if I were to get beyond that, how can I access different properties on the two different types? Like where I need to access employeeNum vs. equipmentNum? I get the same error that the property does not exist on TEntity.

    This is a simplified demo. in my real code base I do not have the ability to change what an IEmployee or IEquipment object look like. I need this component to work with them as they are.

    Continue reading...

Compartilhe esta Página