I have this component:
import React from 'react'
export interface IForEachProps {
each: any[]
children: <T>(item: T, index: number) => JSX.Element
given?: boolean
key?: (item: any) => any
}
export const For: React.FC<IForEachProps> = ({ each, children, key, given = true }) => {
if (!given) return null
return (
<>
{each.map((item, index) => (
<React.Fragment key={key ? key(item) : index}>{children(item, index)}</React.Fragment>
))}
</>
)
}
I have been unsuccessful in my attempts to infer the type of the each prop, as this could be any array. What I want, looking at the example below is for the compiler to infer from the input array that the parameter in the callback is in fact a string.
const list: string[] = ['hello']
<For each={list}>
{(item) => (
<div>{item.length}</div>
)}
</For>