reactjs 键入'T[string]|T[数量]|“T[symbol]”不能赋值给类型“ReactNode”, typescript 错误

juud5qan  于 2023-05-06  发布在  React
关注(0)|答案(1)|浏览(201)

App.tsx

import rows from "./data.json";

type ColumnKeys = keyof (typeof rows)[0];

export interface ColumnType {
  key: ColumnKeys; 
  label: string;
};

const columns: ColumnType[] = [
  { key: "id", label: "ID" },
  { key: "first_name", label: "First name" },
  { key: "last_name", label: "Last name" },
  { key: "email", label: "Email" },
  { key: "phone_no", label: "Phone No." },
  { key: "address", label: "Address" },
];

function App() {
  return (
    <div className="App">
      <Datatable
        {...{ columns, rows }}
      />
    </div>
  );
}

export default App;

types.ts

export type HeaderCell<DataType> = keyof DataType;

export type RowType<DataType> = DataType;

export interface ColumnType<DataType> {
  key: HeaderCell<DataType>;
  label: string;
}

*Datatable.tsx

import React, { Key } from "react";
import "./Datatable.css";
import { ColumnType, HeaderCell, RowType } from "../type";

interface DatatableProps<DataType> {
  columns: ColumnType<DataType>[];
  rows: RowType<DataType>[];
}

function Datatable<T>({ columns, rows, sorting }: DatatableProps<T>)  {

  return (
    <>
      <table id="resizeMe" className="table">
        <thead className="table-header">
          <tr className="table-row">
            {columns.map((column, colIndex) => (
              <th
                key={column.key as Key}
              >
                <div className="table-header-data">
                  {column.label}
                </div>
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((row) => {
            return (
              <tr
                key={row.id} **Property 'id' does not exist on type 'T'.ts(2339)**
                className="table-row"
              >
                {columns.map((column) => (
                  <td
                    key={column.key as Key}
                  >
                    {row[column.key]} **Type 'T[string] | T[number] | T[symbol]' is not assignable to type 'ReactNode'.**
                  </td>
                ))}
              </tr>
            );
          })}
        </tbody>
      </table>
    </>
  );
};

export default Datatable;

我有datatable,它以行和列作为动态数据的 prop 。所以,这就是为什么我使用泛型,但得到错误。

获取这些错误-

1.属性“id”在类型“T”上不存在。ts(2339)
1.键入'T[string]|T[数量]|“T[symbol]”不能赋值给类型“ReactNode”。

现在,在types.ts中,如果我更改RowType,则第一个错误将被解决。

导出类型RowType = DataType & {id?};

gpfsuwkq

gpfsuwkq1#

第一个错误的解决方案-

export type RowType<T> = T & {id?:number};

第二个错误的解决方案-

{row[column.key] as string | number}

相关问题