TS2339:打字稿中来自 @type/反应表的类型上不存在属性'Cell'



我使用@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();
});
});

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

您可以通过使createColumn函数通用来绕过此问题。它强制colDef可分配给TableColumn,但不扩展类型。

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

现在,由于Cell期望使用完整的CellProps进行调用,因此在链的下游会出现一个错误。


更新:

当前设置将列配置中有效的Cell的道具类型推断为CellProps<ColumnValue, any>。这意味着您可以只编写Cell({value}) {而不指定道具类型。

您不能使用Cell的推断道具类型,也不能使用的typescript来推断您的特定Cell只使用这些道具中的道具value(至少在没有一些高级typescript技巧的情况下(。

声明Cell只需要一个值道具很容易,但必须明确声明。

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.hyperlink可能是string,这将是Typescript错误。您应该将它封装在一个片段中,要么封装在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" }
})}
</>
);

最新更新