Generic React Components
When props are generic like this:
inteface SelectProps<T> {
options: T[];
onChange: (value: T) => void;
}
function CoolSelect<T> (props: SelectProps<T>) {
// ...
}
The generic part can be specified in JSX like this:
interface Fruit {
name: string;
isFruit: boolean
}
const fruits = [
{ name: 'Pumpkin', isFruit: true },
{ name: 'Avocado', isFruit: true },
{ name: 'Cucumber', isFruit: true },
{ name: 'Bell Pepper', isFruit: true },
]
funciton App() {
return <CoolSelect<Fruit> options={fruits} />
}
See it? <CoolSelect<Fruit> options={fruits} />
Now when crafting the onChange
function in this example, it's type will be infered as this:
type OnChange = (value: Fruit) => void
funciton App() {
return (
<CoolSelect<Fruit>
options={fruits}
onChange={value => {
if (value.isFruit && value.name === 'Bell Pepper') {
console.log("You're blowing my mind dude!")
}
}}
/>
)
}
*This syntax is available in Typescript v2.9+
Tweet