【问题标题】:TS2339: Property 'Cell' does not exist on type from @type/react-table in typescriptTS2339:打字稿中 @type/react-table 的类型上不存在属性“单元格”
【发布时间】:2021-03-19 14:20:04
【问题描述】:

我使用@type/react-table 为我的表设置列,我的IDE 出现错误,抱怨Cell 的类型不正确。我认为它是由Cell 引起的,是@type/react-table 的可选类型我该如何解决这个问题?

//column.tsx
import {Column, Cell} from 'react-table';

export interface ColumnValue {
    [key: string]: any;
}
export type TableColumn = Column<ColumnValue>
export function createColumn(colDef: TableColumn): TableColumn {
  return colDef;
}
export const name = createColumn({
  id: 'name',
  Header: 'Name Column',
  Cell({value}}) {
    return value.hyperlink
  },
});


//column.test.tsx
import {render} from '@testing-library/react';
import {name} from './Name';

describe('Test Name Column', () => {

  it('shows the name', () => {
    const {getByText} = render(
      name.Cell({
      // Error show TS2339: Property 'Cell' does not exist on type 'TableColumn'
        value: {hyperlink: 'asadasd'}}),
      })
    );
    expect(getByText('i am name')).toBeTruthy();
  });
});

【问题讨论】:

标签: typescript typescript-typings typescript-generics react-table-v7 react-table-v6


【解决方案1】:

Column 的定义是一组描述可能的列配置的不同类型的联合。只有其中一些具有Cell 属性。 ColumnGroup 没有。因此,您不确定Column 类型的变量是否支持Cell 属性。

您可以通过将 createColumn 函数设为通用来解决此问题。它强制 colDef 可分配给 TableColumn 但不会扩大类型。

export function createColumn<C extends TableColumn>(colDef: C): C {
  return colDef;
}

现在您会在更进一步的链中得到一个错误,因为 Cell 预计会以完整的 CellProps 调用。


更新:

当前设置将您的列配置中有效Cell 的道具类型推断为CellProps&lt;ColumnValue, any&gt;。这意味着你可以直接写 Cell({value}) { 而不指定 props 类型。

您不能使用 Cell 的推断 props 类型,并且还获取打字稿来推断您的特定 Cell 仅使用这些道具 value (至少不是没有一些高级 Typescript 技巧)。

很容易声明 Cell 只需要一个 value 属性,但你必须明确声明。

export const name = createColumn({
  id: 'name',
  Header: 'Name Column',
  Cell({value}: {value: ColumnValue}) {
    return value.hyperlink
  },
});

React 测试库的 render 方法期望使用 ReactElement 调用。由于ColumnValue {[key: string]: any;} 的松散定义,现在您的Cell 返回any。但可能value.hyperlinkstring,这将是一个打字稿错误。您应该将其包装在一个片段中,可以是 Cell 本身,也可以是 render

export const name = createColumn({
  id: 'name',
  Header: 'Name Column',
  Cell({value}: {value: {hyperlink: string}}) {
    return value.hyperlink
  },
});

上面的定义会导致测试出错,所以需要这样做:

const { getByText } = render(
  <>
    {name.Cell({
      value: { hyperlink: "asadasd" }
    })}
  </>
);

【讨论】:

  • 我在更改您的建议后收到错误TS2345: Argument of type '{ value: any; }' is not assignable to parameter of type 'PropsWithChildren&lt;CellProps&lt; ColumnValue, any&gt;&gt;'.   Type '{ value: any; }' is missing the following properties from type 'TableInstance&lt; ColumnValue&gt;': state, plugins, dispatch, columns, and 70 more.
  • 是的,这就是我所说的“现在你会在更远的地方得到一个错误,因为 Cell 期望使用完整的 CellProps 被调用。”
  • 我明白了。有什么解决办法吗?
  • 谢谢。但是我在Cell 中声明value 的类型的任何其他方式都只是一个简单的例子。但是,在我真正的应用程序中。这很复杂
猜你喜欢
  • 2019-08-16
  • 2021-01-05
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 2020-11-10
  • 2016-12-12
  • 1970-01-01
  • 2017-08-07
相关资源
最近更新 更多