Not sure if this is possible, but it's related to keyof
which I'm having a hard time wrapping my mind around...
I currently have this interface:
interface Column<T> {
header: string;
field: keyof T;
format?: (value: any) => string;
}
First usage for it is to create something that renders a table, given a list of objects and columns.
const rows = [{name: 'Alice', age: 18}, {name: 'Bob', age: 12}];
type Row = typeof rows[0];
const columns: Column<Row>[] = [
{
header: 'Name',
field: 'name',
format: value => value.toUpperCase(),
},
{
header: 'Age',
field: 'age',
format: value => value.toLocaleString(),
},
];
const renderTable = <T>(rows: T[], columns: Columns<T>[]) { ... }
renderTable(rows, columns);
Is there a way to get rid of the any
type here in the format
function? To somehow "link" the keyof T
of field
with the value
of format
? I.e. for the first column value
should be string
, and for the second it should be number
?
(I know it would be very easy to just print these out manually, but there's also going to be added some auto-magic stuff to this table which will make use of field
and format
)