M
M
merss2019-06-03 11:53:03
JavaScript
merss, 2019-06-03 11:53:03

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} />;
};

Typescript throws an error - Property 'name' does not exist on type 'T', but am I passing the FiltersType interface to the Filters component?
How to make it possible to pass dynamic type to the Filters component?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-06-03
@merss

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 question

Ask a Question

731 491 924 answers to any question