我有通用组件(具有以下类型):
const Search = <T extends object | number | string, K extends T extends object ? keyof T : T>(props: SearchProps<T,K>) => {
const { data, searchKey } = props;
return (
<div> Test </div>
)
};
export type SearchProps<T, K> = {
type: SearchType;
setSearcheData: Function;
data: T[];
searchKey: K;
};
您应该能够像在示例中一样使用它:
const dataObject: dataObjectType = [
{
name: '1',
id: 1,
},
{
name: '2',
id: 2,
}
];
const dataString = ['1', '2'];
<Search
data={dataString}
searchKey={'string'}
type={SearchType.SingleIcon}
setSearcheData={()=>{}}
/>
我应该能够data
作为 Array 传递,并且searchKey
好像 T 是对象、它的键或只是一个类型。
但是当我尝试做类似的事情时
data[0][`${searchKey}`]
我收到了一个 TS 错误。
我尝试了类似的东西
typeof data[0] === 'object' or Object.keys(data[0]).find(key => key === `${searchKey}`)
但它不起作用。
有任何想法吗?