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

React Hook类型错误:'{ items: string[]; }'无法赋值指定联合类型

问题背景

我有一个泛型组件Table<T>,定义如下:

interface Props<T> {
  cells: Array<TableCell<T>>;
  headers: TableHeader[];
  items: T[];
}

export default function Table<T>({ cells, headers, items }: Props<T>) {
  ...
}

为避免在每个使用Table的文件中重复导入Table、TableCell和TableHeader,我创建了useTable Hook:

import { useState } from 'react';

import Table from '../components/Table';
import type TableCell from '../types/TableCell';
import type TableHeader from '../types/TableHeader';

export default function useTable<T>() {
  const [tableCells, setTableCells] = useState<Array<TableCell<T>>>([]);
  const [tableHeaders, setTableHeaders] = useState<TableHeader[]>([]);

  function CurriedTable(items: T[]) {
    return (
      <Table<T>
        cells={tableCells}
        headers={tableHeaders}
        items={items}
      />
    );
  }

  return {
    setTableCells,
    setTableHeaders,
    Table: CurriedTable,
  };
}

但调用useTable<string>()并使用返回的Table组件时,出现错误:

Type '{ items: string[]; }' is not assignable to type 'IntrinsicAttributes & string[]'.
  Property 'items' does not exist on type 'IntrinsicAttributes & string[]'.

悬停返回的Table组件显示它期望items为string[]类型,而我传入的属性确实是该类型。若不传任何属性,会出现错误:

Type '{}' is missing the following properties from type 'string[]': length, pop, push, concat, and 29 more.
错误原因

问题核心在于CurriedTable的定义与React组件的调用逻辑不匹配:

  • 你把CurriedTable写成了接收单个数组参数的普通函数,但在使用时却以React组件的语法(<Table items={xxx} />)调用它。
  • React组件要求接收的参数是props对象,而非单个值。当你用组件语法调用时,React实际传递的是{ items: string[] }这样的对象,这和函数期望的string[]类型完全不兼容,因此触发类型错误。
  • 若不传任何属性,React会传递空对象{},自然无法匹配string[]类型,于是提示缺少数组的核心属性与方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 11:02:36