Answer the question
In order to leave comments, you need to log in
Why does typescript throw an error when using generic?
Full code here https://codesandbox.io/s/cocky-swanson-j6zt6
interface FiltersProps<T> {
filters: T[];
}
const Filters = <T extends object>(props: FiltersProps<T>) => {
const { filters } = props;
return (
<div>
{filters.map((filter: T) => {
return (
<div>
{filter.title}
{filter.name}
</div>
);
})}
</div>
);
};
interface FiltersType {
name?: string;
title?: string;
}
const Main = (props: Props) => {
return <Filters<FiltersType> filters={filters} />;
};
Answer the question
In order to leave comments, you need to log in
Generics are not needed here.
interface Filter {
name?: string;
title?: string;
}
interface FiltersProps {
filters: Filter[];
}
const Filters: React.FC<FiltersProps> = ({ filters }) => (
<div>
{filters.map((filter: Filter) => (
<div key={filter.name}>
{filter.title}
{filter.name}
</div>
))}
</div>
);
const Main: React.FC = () => (
<Filters filters={filters} />
);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question