Home > Net >  Generic type for @Input() decorator angular
Generic type for @Input() decorator angular

Time:11-25

I want to add generic type to my @Input() decorator but I have some issues.

My attempts

Here I'm getting this error An accessor cannot have type parameters.

@Input() set tableData<K extends keyof IUser extends IOrder>(data: K) {
  if (data) {
    this.length = data['hydra:totalItems'];
    this.dataSource.sort = this.dataSourceSort;
    this.dataSource = new MatTableDataSource(data['hydra:member']);
    this.selectedRows = [];
    this.loading = false;
  }
}
@Input() set tableData<K extends keyof IOrder>(data: K) {
  if (data) {
    this.length = data['hydra:totalItems'];
    this.dataSource.sort = this.dataSourceSort;
    this.dataSource = new MatTableDataSource(data['hydra:member']);
    this.selectedRows = [];
    this.loading = false;
  }
}

CodePudding user response:

By defining a setter as generic, you basically have to mark the corresponding class (component) as generic and define the type restrictions on class level. It seem like there is an open issue for actual typescript support to generically define accessors: https://github.com/microsoft/TypeScript/issues/35986

To actually define the generic on class level, you can define it as following:

export class YourComponent<K extends keyof IOrder>  {

  @Input() set name(data: K) {
    if (data) {
      this.length = data['hydra:totalItems'];
      this.dataSource.sort = this.dataSourceSort;
      this.dataSource = new MatTableDataSource(data['hydra:member']);
      this.selectedRows = [];
      this.loading = false;
    }
  }
}

Nevertheless it seems like your types are not really matching, since keyof produces a string or numeric literal union of the following object. Therefore data could only be of type string, which is obviously not the case, since you are trying to access properties of data.

  • Related