简体   繁体   English

Typescript:动态推断类型

[英]Typescript: Inferring types dynamically

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>
   )
}

I have a table component where i can pass the api url and it calls it on mount.我有一个表格组件,我可以在其中传递 api url 并在安装时调用它。 I'm passing down the headers array which is an array of text and value.我正在传递 headers 数组,它是一个文本和值的数组。 Text the one that is shown on the header and value is the property of the response from the api.文本显示在 header 上,值是 api 响应的属性。 Basically I want to infer the type on onClickRow(item) and it is based on the value property in the headers array.基本上我想推断 onClickRow(item) 上的类型,它基于 headers 数组中的 value 属性。 Is it possible?可能吗?

Sample:样本:

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

item in onClickRow should look like this: onClickRow 中的项目应如下所示:

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

It's possible, but the union of the header values must be provided.这是可能的,但必须提供 header 值的并集。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM