- I use ItemMap to map each type to its corresponding item.
type ItemMap = {
write: string[];
see: string[];
find: DataLibraryType[];
read: UploadFile[];
};
- The generic parameter K of SearchListProps is used to realize that different currentWay corresponds to different list types.
interface SearchListProps<K extends WaysType> {
currentWay: K;
list: ItemMap[K];
onClick: (val: ItemMap[K][number]) => void;
onRemove?: () => void;
}
type WaysType = 'write' | 'read' | 'see' | 'find'
I want the list to be able to infer different types based on the value of currentWay
But ts error
The parameter “index” implicitly has type “any”, but better types can be inferred from usage. ts(7044)
and When currentWay = ‘read’ , the list type error
error msg : Attribute “name” does not exist on type “string | DataLibraryType | UploadFile” Attribute “name” does not exist on type “string”.
const SearchList = <K extends WaysType>(props: SearchListProps<K>) => {
const { currentWay, list, onClick, onRemove } = props
switch (currentWay) {
case 'write':
case 'see':
case 'find':
return <div>
{
list.map((r, index) => {
const itemName = currentWay === 'find' ? r?.name : r
return <div key={index}>{itemName}</div>
})
}
</div>
case 'read':
const currentFile = list?.[0]
// Attribute “name” does not exist on type “string | DataLibraryType | UploadFile<any>” Attribute “name” does not exist on type “string”.
const fileType = getFileExtension(currentFile?.name) || 'file'
if (!currentFile) {
return <></>
}
return <div>{currentFile?.desc}</div>
default:
return <></>
}
}
I want the list to be able to infer different types based on the value of currentWay
switch (currentWay) {
case 'write':
case 'see':
case 'find':
return <div>
{
list.map((r, index) => {
const itemName = currentWay === 'find' ? r?.name : r
return <div key={index}>{itemName}</div>
})
}
</div>
case 'read':
// list type is UploadFile[] no error
return <div>... </div>