reactjstypescriptalgoliareact-instantsearch

How to type custom widget for Algolia React instant search?


I'm trying to correctly type my connected list of Hits from algolia instant search.

My custom Hits component:

type Props = { hits: User[]; onSelectUser: (user: User) => void };

const SearchResults: React.FC<Props> = ({ hits, onSelectUser }) => {
  return hits.map((hit: User) => (
    <UserCard user={hit} onSelectUser={onSelectUser} />
  ));
};

export default connectHits<Props>(SearchResults);

When I try to use the component:

<Hits hitComponent={() => (<SearchResults onSelectUser={setSelectedUser} />)}/>

I get a TS error that onSelectUser does not exist on that component... When I ignore this TS error I see that the props are available within in the SearchResults component.

How should I type my component correctly to ensure that the typings are still working correctly?


Solution

  • You can extend the HitsProvided interface exposed by react-instantsearch-core.

    import { HitsProvided } from "react-instantsearch-core";
    
    // ...
    
    type Props = HitsProvided<UserRecord> & {
      onSelectUser: (user: User) => void;
    };
    
    const SearchResults: React.FC<Props> = ({ hits, onSelectUser }) => {
      return hits.map((hit: User) => (
        <UserCard user={hit} onSelectUser={onSelectUser} />
      ));
    };
    
    export default connectHits<Props, UserRecord>(SearchResults);
    

    UserRecord would describe the shape of your record (not the shape of the hit returned by the API, only the attributes).