You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中为@Input()装饰器添加泛型类型时遇到错误

Angular @Input() setter 添加泛型报错 "An accessor cannot have type parameters" 的解决办法

你遇到的错误是因为TypeScript不允许给访问器(get/set方法)单独添加泛型类型参数,泛型只能定义在类、函数或接口层级,不能直接加在setter上。

看你代码的意图,应该是想让tableData接收带有hydra:totalItems和hydra:member属性的IOrder或IUser相关数据,这里给你两种可行的实现方案:

方案一:给组件类添加泛型参数

把泛型定义在组件类上,让整个组件和输入数据的类型绑定,这是最规范的做法:

import { Component, Input } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';

// 先定义你的基础接口
interface IOrder {
  // 补充IOrder的属性定义
}

interface IUser {
  // 补充IUser的属性定义
}

// 封装带有hydra分页属性的通用响应类型
interface HydraResponse<T> {
  'hydra:totalItems': number;
  'hydra:member': T[];
}

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html'
})
export class TableComponent<T extends IOrder | IUser> {
  length = 0;
  dataSource = new MatTableDataSource<T>();
  dataSourceSort: any; // 假设你已初始化排序实例
  selectedRows: T[] = [];
  loading = true;

  @Input() set tableData(data: HydraResponse<T>) {
    if (!data) return;
    
    this.length = data['hydra:totalItems'];
    this.dataSource.sort = this.dataSourceSort;
    // 直接更新dataSource的data属性,无需重新实例化
    this.dataSource.data = data['hydra:member'];
    this.selectedRows = [];
    this.loading = false;
  }
}

使用组件时,TypeScript会自动根据传入的tableData类型推断泛型参数,或者你也可以显式指定:

<app-table [tableData]="orderHydraData"></app-table>
<!-- 显式指定类型 -->
<app-table<IOrder> [tableData]="orderHydraData"></app-table>

方案二:直接用类型约束输入数据

如果不需要整个组件泛型,可以直接给tableData定义符合要求的类型:

import { Component, Input } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';

interface IOrder { /* 属性定义 */ }
interface IUser { /* 属性定义 */ }

type HydraOrderResponse = IOrder & {
  'hydra:totalItems': number;
  'hydra:member': IOrder[];
};

type HydraUserResponse = IUser & {
  'hydra:totalItems': number;
  'hydra:member': IUser[];
};

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html'
})
export class TableComponent {
  length = 0;
  dataSource = new MatTableDataSource<IOrder | IUser>();
  dataSourceSort: any;
  selectedRows: (IOrder | IUser)[] = [];
  loading = true;

  @Input() set tableData(data: HydraOrderResponse | HydraUserResponse) {
    if (!data) return;
    
    this.length = data['hydra:totalItems'];
    this.dataSource.sort = this.dataSourceSort;
    this.dataSource.data = data['hydra:member'];
    this.selectedRows = [];
    this.loading = false;
  }
}

额外提示

你之前的代码里重新实例化MatTableDataSource是没必要的,直接更新其data属性即可,这样能保留已有的配置(比如排序、分页实例)。

内容的提问来源于stack exchange,提问作者Sergio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:05:21