首页 > 解决方案 > 在“未知”类型上找不到具有“字符串”类型参数的索引签名

问题描述

我正在尝试创建一个通用表组件,它将接收一组对象并呈现一个表组件。

使用该组件的父组件Cell需要传递columns(下面提供的示例)对象,以便决定从数据中呈现哪些字段。

我的问题是,在我的Cell组件中,我试图为指定列呈现该行的内容,它给了我No index signature with a parameter of type 'string' was found on type 'unknown'.错误。

这是我的类型定义和 Cell 组件。

注意:Cell组件接收数据形状的通用类型。

列类型

interface ColumnType<D> {
  field: Exclude<keyof typeof D, symbol>; // Excluding symbol as it gives some other errors
}

单元格组件道具

interface ICellProps<D> {
  row: D;
  col: ColumnType<D>;
}

细胞成分

function Cell<D>(props: ICellProps<D>) {
  const { row, col } = props;

  return <td>{row[col.field]}</td>; // Error happens here for row[col.field]
}

基本上,对于这个示例数据;

const data = [
  { name: "John", age: 25 },
  { name: "Jane", age: 21 },
];

并为此列列表;

const columns = [
  { field: "name", verbose: "Name" },
  { field: "age", verbose: "Age" },
];

我希望row对象只接受“姓名”和“年龄”,这应该是这里的情况,因为在Cell组件内部,col类型看起来像ColumnType<D>,但它给了我以下错误:

打字稿错误

如果我row[col.field as keyof D]在错误消失时编写它,但我正在寻找一种解决方案来解决我的类型定义中的问题。我不是 100% 确定这里最好的方法是什么。我想,我设计类型定义的方式应该可以工作,因为rowistype of Dcol.fieldis keyof D

任何帮助表示赞赏。

标签: reactjstypescripttypestypescript-typingstypescript-generics

解决方案


推荐阅读