Why typescript throws an error when you use generic?

Full code here https://codesandbox.io/s/cocky-swanson-j6zt6
FiltersProps interface<T> {
 filters: T[];
}

const Filters = <T extends object>(props: FiltersProps<T>) => {
 const { filters } = props;
 return (
the <div>
 {filters.map((filter: T) => {
 return (
the <div>
{filter.title}
{filter.name}
</div>
);
})}
</div>
);
};

interface FiltersType {
 name?: string;
 title?: string;
}

const Main = (props: Props) => {
 return <Filters<FiltersType> filters={filters} />;
};


Typescript gives an error - Property "name" does not exist in type "T", but I piredeu interface FiltersType component Filters?
How to make so you can pass dynamically to a component type Filters?
March 23rd 20 at 18:52
2 answers
March 23rd 20 at 18:54
Solution
Don't need generics here.
interface Filter {
 name?: string;
 title?: string;
}

interface FiltersProps {
 filters: Filter[];
}

const Filters: React.FC<FiltersProps> = ({ filters }) => (
the <div>
 {filters.map((filter: Filter) => (
 <div key={filter.name}>
{filter.title}
{filter.name}
</div>
))}
</div>
);

const Main: React.FC = () => (
 <Filters={filters} />
);
March 23rd 20 at 18:56
Solution
<T extends object>
replace
<T extends {name?: string; title?: string} >

Otherwise TS does not know what field name have T - and therefore he rightly complains. In General, as you said, generics you likely don't need. At least in this example - dynamic type transfer is not necessary, you do not depend. Enough to just a pass-through type cited to FiltersType

Find more questions by tags ReactTypeScriptJavaScript