打字稿:动态推断类型

时间:2021-04-06 09:50:15

标签: reactjs typescript

interface TableProps {
   headers: {
      text: string;
      value: string;
   }[];
   onClickRow: (item: unkown) => void;
   api: {
        url: string;
   };
}
        
const Table: React.FC<TableProps> = ({headers, onClickRow, api}) => {
   const [items, setItems] = useState([]);

   useEffect(() => {
      here i call the api and set it to items
   },[])
 
   return (
      <table>
         <thead>
            <tr>
               {headers.map((header, index) => (
                   <td key={index}>
                       {header.text}
                   </td>
                ))}
            </tr>
         </thead>
         <tbody>
            {items.map((item: any, index) => (
               <tr onClick={() => onClickRow(item)}>
                   {headers.map((header, headerIndex) => (
                       <TableCell key={headerIndex}>
                           {item[header.value]}
                       </TableCell>
                    ))}
               </tr>
            ))}
         </tbody>
      </table>
   )
}

我有一个表组件,我可以在其中传递 api url 并在挂载时调用它。我正在传递 headers 数组,它是一个文本和值数组。文本显示在标题上,值是来自 api 的响应的属性。基本上我想推断 onClickRow(item) 的类型,它基于 headers 数组中的 value 属性。可能吗?

示例:

headers: [
  {text: 'Sample Text', value: 'FirstProperty'},
  {text: 'Sample Text', value: 'SecondProperty'},
]

onClickRow 中的项目应如下所示:

{
  FirstProperty: string | number | boolean
  SecondProperty: string | number | boolean
}

1 个答案:

答案 0 :(得分:0)

可以,但必须提供标头值的联合。

interface TableProps<H extends string> {
  headers: ReadonlyArray<{
    text: string
    value: H
  }>
  onClickRow: (item: Readonly<Record<H, string | number | boolean>>) => void
  api: { url: string }
}