在给定以下条件的情况下,Render方法的参数value
的类型为string | number
.
如何确保它的类型为T[dataIndex]
,在 case dataIndex: 'name'
中为string
,在 case dataIndex: 'id'
中为number
?
import * as React from 'react'
type Col<T extends object, K extends keyof T> = {
title: string;
dataIndex: K;
render: (value: T[K]) => React.ReactNode;
};
function Tab<T extends object, K extends keyof T = keyof T>(list: T[], cols: Col<T, K>[]): JSX.Element {
return (
<table>
<thead>
<tr>
{cols.map(col => (
<th key={col.title}>{col.title}</th>
))}
</tr>
</thead>
<tbody>
{list.map((item, i) => (
<tr key={i}>
{cols.map(col => (
<td key={col.title} children={col.render(item[col.dataIndex])} />
))}
</tr>
))}
</tbody>
</table>
);
}
Tab(
[
{ id: 1, name: 'Hello' },
{ id: 2, name: 'World' }
],
[
{
title: 'Name',
dataIndex: 'name',
render: value => <span>{value.length}</span>
},
{
title: 'Id',
dataIndex: 'id',
render: value => <span>{value}</span>
}
]
);