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