首页 > 解决方案 > TypeScript 泛型类型作为参数

问题描述

请帮我解决这种错误 core.js:6157 ERROR TypeError: Cannot read property 'displayProp' of undefined for this code:

export class Company {
    companyName: string;
    cif: string;

    static tableName: string = 'Companies';
    static displayProp: string = 'companyName';
}`enter code here`


export class GenericListComponent<T> implements OnInit {

  @Input() listItems: T[] = [];
  @Input() modelType: { new(...args: any[]): T; };

  constructor() { }

  ngOnInit(): void {
    console.log(this.listItems);
  }

}

 generic-list.component.html
<div *ngIf="listItems">
    <ul>
        <li *ngFor="let listItem of listItems">
            <h4>{{listItem[modelType].displayProp}}</h4>
        </li>
    </ul>
</div>

export class ListExComponent implements OnInit {

  companyRef: Company;

  companies: Company[] = [
    { companyName: "Comp 1", cif: "123" },
    { companyName: "Comp 2", cif: "456" }
  ];

  constructor() { }

  ngOnInit(): void {
  }

}

list-ex.component.html
<div>
    <app-generic-list #childComponentId [listItems]="companies" [modelType]="companyRef"></app-generic-list>
</div>

app.component.html
<app-list-ex></app-list-ex>

我在这里找到了这段代码: https ://levelup.gitconnected.com/typescript-generic-types-as-parameters-882e692073d5 但是坏了。

谢谢。

标签: angulartypescripttypescript-generics

解决方案


推荐阅读