I use the @type/react-table to set up the column for my table and I have error on my IDE complain that Cell is not under correct type. I assume it is caused by Cell is optional type from @type/react-table how can I solve this?
//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();
});
});
The definition of
Columnis a union of a bunch of different types describing possible column configurations. Only some of them have aCellproperty.ColumnGroupdoes not. Therefore you don't know for sure that a variable of typeColumnsupports theCellproperty.You can get around this by making your
createColumnfunction generic. It enforces thatcolDefis assignable toTableColumnbut doesn't widen the type.Now you get an error further down the chain because
Cellexpects to be called with the completeCellProps.Update:
The current setup infers the type of the props for a valid
Cellin your column configuration asCellProps<ColumnValue, any>. This means that you can just writeCell({value}) {without specifying the props type.You cannot make use of the inferred props type for
Cellof and also get typescript to infer that your particularCellonly uses the propvaluefrom those (at least not without some advanced Typescript trickery).It's easy to declare that the
Cellonly needs a value prop, but you have to state that explicitly.The
rendermethod of React Testing Library expects to be called with aReactElement. Right now yourCellreturnsanydue to the loose definition ofColumnValue {[key: string]: any;}. But probablyvalue.hyperlinkis astringwhich would be a Typescript error. You should wrap it in a fragment, either in theCellitself or in therender.The above definition will cause an error in the test so you need to do this: