headlessui icon indicating copy to clipboard operation
headlessui copied to clipboard

TS props type issue when creating own custom reusable Combobox

Open its-monotype opened this issue 3 years ago • 17 comments

What package within Headless UI are you using?

@headlessui/react

What version of that package are you using?

v1.7.14

Describe your issue

I want to integrate Combobox in my UI library, however, I can't create a wrapper with custom styles as we can do in Radix https://www.radix-ui.com/docs/primitives/components/select#custom-apis.

Here is a part of my custom component:

import { Combobox as ComboboxPrimitive } from '@headlessui/react';

export const Combobox = ({
  children,
  ...props
}: React.ComponentProps<typeof ComboboxPrimitive>) => {
  return (
    <ComboboxPrimitive {...props}>
      <div className="relative">{children as React.ReactNode}</div>
    </ComboboxPrimitive>
  );
};

...

Here is a usage example:

export const Multiple = () => {
  const [selectedPeople, setSelectedPeople] = useState<Person[]>([]);

  const handleSelect = (person: Person[]) => {
    setSelectedPeople(person);
  };

  return (
    <Combobox value={selectedPeople} onChange={handleSelect} multiple>
      {selectedPeople.length > 0 && (
        <ul>
          {selectedPeople.map((person) => (
            <li key={person?.id}>{person?.name}</li>
          ))}
        </ul>
      )}
      <Combobox.Input />
      <Combobox.Options>
        {people.map((person) => (
          <Combobox.Option key={person.id} value={person}>
            {person.name}
          </Combobox.Option>
        ))}
      </Combobox.Options>
    </Combobox>
  );
};

but I got this error:

Type 'true' is not assignable to type 'false'.ts(2322)
combobox.d.ts(39, 5): The expected type comes from property 'multiple' which is declared here on type 'IntrinsicAttributes & { value?: unknown; nullable?: false | undefined; multiple?: false | undefined; defaultValue?: unknown; onChange?(value: unknown): void; by?: ((a: unknown, b: unknown) => boolean) | undefined; } & ... 4 more ... & { ...; }'
Type 'true' is not assignable to type 'false'.

its-monotype avatar Apr 15 '23 15:04 its-monotype

I noticed that you have ComboboxProps exported but it needs generics. Is there any example on how to create reusable component?

its-monotype avatar Apr 15 '23 15:04 its-monotype

I just had the same problem. It does not make sense. Any example for this?

andreguerrerosilvera avatar Apr 16 '23 08:04 andreguerrerosilvera

I had to create a wrapper to implement a reusable component. You can check my proposal here.

I guess there is a better way to implement it but for now, this works for my personal project.

Single mode: https://user-images.githubusercontent.com/48815940/232930797-1855baf1-aa8c-46b5-a46b-ba91296f1075.mp4

Multiple mode: https://user-images.githubusercontent.com/48815940/232930820-af5f0306-9c1c-490b-bbeb-83ad29eed1ff.mp4

I think there are still properties to add such as a placeholder, default value, etc. The way I use those components is as follows:

const [filteredAnimals, setFilteredAnimals] = useState(animals);
  
function filterAnimals(query: string) {
    const foundAnimals =
      query === ''
        ? animals
        : animals.filter((animal) =>
            animal.name
              .toLowerCase()
              .replace(/\s+/g, '')
              .includes(query.toLowerCase().replace(/\s+/g, ''))
          );
    setFilteredAnimals(foundAnimals);
  }


function renderAnimal(animal: any) {
    return <span>{animal.name}</span>;
  }

  function getAnimalName(animal: any) {
    return animal.name;
  }

  return (
    <SelectAutocomplete
      items={filteredAnimals}
      noResultsMessage="No hay resultados"
      filterItems={filterAnimals}
      renderItem={renderAnimal}
      labelExtractor={getAnimalName}
      multiple
    />
  );

andreguerrerosilvera avatar Apr 19 '23 00:04 andreguerrerosilvera

When you have more properties to be used on your custom reusable component, problem increases. Like having multiple and nullable

ayhanap avatar Apr 19 '23 13:04 ayhanap

You won't be able to just paste in the prop with React.ComponentProps<typeof ComboboxPrimitive>) and just call it a day.

As @its-monotype mentioned, ComboboxProps is generic. By passing this into React.ComponentProps, the generic types are getting converted into unknown somewhere down the line, and TypeScript now assumes your Combobox is not multiple, because it doesn't know if unknown is an array.

The polymorphic type is really complicated, and there's even unsafe casting in the code base, so you would probably have to do something similar.

pting-me avatar Apr 27 '23 21:04 pting-me

ComboBox has an issue with props in general.

I'm using the newest version, 1.7.14. I simply copied the example of multiple https://headlessui.com/react/combobox#selecting-multiple-values

import { Combobox } from "@headlessui/react";

const people = [
  { id: 1, name: "Durward Reynolds" },
  { id: 2, name: "Kenton Towne" },
  { id: 3, name: "Therese Wunsch" },
  { id: 4, name: "Benedict Kessler" },
  { id: 5, name: "Katelyn Rohan" },
];

function MyCombobox() {
  const [selectedPeople, setSelectedPeople] = useState([people[0], people[1]]);

  return (
    <Combobox value={selectedPeople} onChange={setSelectedPeople} multiple>
      {selectedPeople.length > 0 && (
        <ul>
          {selectedPeople.map((person) => (
            <li key={person.id}>{person.name}</li>
          ))}
        </ul>
      )}
      <Combobox.Input />
      <Combobox.Options>
        {people.map((person) => (
          <Combobox.Option key={person.id} value={person}>
            {person.name}
          </Combobox.Option>
        ))}
      </Combobox.Options>
    </Combobox>
  );
}

export default MyCombobox;

And getting this as an error.

src/components/Select/Multiple.tsx:19:7 - error TS2769: No overload matches this call.
  The last overload gave the following error.
    Type 'true' is not assignable to type 'false'.

19       multiple={true}
         ~~~~~~~~

  ../../node_modules/@headlessui/react/dist/components/combobox/combobox.d.ts:39:5
    39     multiple?: false;
           ~~~~~~~~
    The expected type comes from property 'multiple' which is declared here on type 'IntrinsicAttributes & { value?: SetStateAction<{ id: number; name: string; }[]> | undefined; nullable?: false | undefined; multiple?: false | undefined; defaultValue?: SetStateAction<...> | undefined; onChange?(value: SetStateAction<...>): void; by?: ByComparator<...> | undefined; } & CleanProps<...> & OurProps<...>...'
  ../../node_modules/@headlessui/react/dist/components/combobox/combobox.d.ts:111:5
    111     <TValue, TTag extends ElementType = typeof DEFAULT_COMBOBOX_TAG>(props: ComboboxProps<TValue, false, false, TTag> & RefProp<typeof ComboboxFn>): JSX.Element;
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The last overload is declared here.

A fix to this would be much appreciated

reuel88 avatar May 16 '23 12:05 reuel88

I've created own conditional mapping to match ComboBox

export type SelectProps<T, TMultiple = boolean> = TMultiple extends true ? {
  onChange: (value: SelectOptionType<T>[]) => void;
  value: SelectOptionType<T>[];
  multiple: TMultiple;
} & SelectBaseProps<T> : {
  value?: SelectOptionType<T> | undefined;
  onChange?: (value: SelectOptionType<T> | undefined) => void;
  multiple: TMultiple;
} & SelectBaseProps<T>;

It's working properly in all cases and in the rest of code, but I cannot pass props to ComboBox itself:

<Combobox 
   value={props.value} 
   onChange={props.onChange} 
   nullable={true} 
   disabled={props.disabled} 
   multiple={props.multiple} 
   by="id">

Because of error:

TS2769: No overload matches this call.   The last overload gave the following error.     Type 'SelectOptionType<T> | SelectOptionType<T>[] | undefined' is not assignable to type 'SelectOptionType<T>[] | undefined[] | { label: string; value: T; id?: string | undefined; }[] | undefined'.       Type 'SelectOptionType<T>' is not assignable to type 'SelectOptionType<T>[] | undefined[] | { label: string; value: T; id?: string | undefined; }[] | undefined'.         Type '((value: SelectOptionType<T> | undefined) => void) | ((value: SelectOptionType<T>[]) => void) | undefined' is not assignable to type '((value: SelectOptionType<T>[] | undefined[] | { label: string; value: T; id?: string | undefined; }[]) => void) | undefined'.           Type '(value: SelectOptionType<T> | undefined) => void' is not assignable to type '(value: SelectOptionType<T>[] | undefined[] | { label: string; value: T; id?: string | undefined; }[]) => void'.             Types of parameters 'value' and 'value' are incompatible.               Type 'SelectOptionType<T>[] | undefined[] | { label: string; value: T; id?: string | undefined; }[]' is not assignable to type 'SelectOptionType<T> | undefined'.                 Type 'SelectOptionType<T>[]' is missing the following properties from type 'SelectOptionType<T>': label, value                   Type 'true' is not assignable to type 'false'.                     Type 'boolean' is not assignable to type 'true'.                       Type 'string' is not assignable to type '(a: SelectOptionType<T> | undefined, b: SelectOptionType<T> | undefined) => boolean'.  combobox.d.ts(30, 5): The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & ComboboxProps<SelectOptionType<T> | SelectOptionType<T>[] | undefined, false, true, ExoticComponent<{ children?: ReactNode; }>>' combobox.d.ts(55, 18): The last overload is declared here.

michalzubkowicz avatar Jun 03 '23 10:06 michalzubkowicz

Listbox types works fine. If that helps. 😄

Frans06 avatar Jun 13 '23 23:06 Frans06

Please fix this... :'(

tempSt69 avatar Jun 29 '23 13:06 tempSt69

My "workaround" - provide genetic type to <Combobox /> by

<Combobox<T> .../>
// define People interface
interface People {
  id: number;
  name: string;
}

// hardcode options
const people: People[] = [
  { id: 1, name: "Durward Reynolds" },
  { id: 2, name: "Kenton Towne" },
  { id: 3, name: "Therese Wunsch" },
  { id: 4, name: "Benedict Kessler" },
  { id: 5, name: "Katelyn Rohan" },
];

// MyCombobox
export function MyCombobox(_props: Props): ReactNode {
  const [selectedPeople, setSelectedPeople] = useState<People[]>([
    people[0],
  ]);
  return (
    <Combobox<People>
      multiple
      value={selectedPeople}
      onChange={setSelectedPeople}
    >
      {selectedPeople.length > 0 ? (
        <ul>
          {selectedPeople.map((person) => (
            <li key={person.id}>{person.name}</li>
          ))}
        </ul>
      ) : null}
      <Combobox.Input />
      <Combobox.Options>
        {people.map((person) => (
          <Combobox.Option key={person.id} value={person}>
            {person.name}
          </Combobox.Option>
        ))}
      </Combobox.Options>
    </Combobox>
  )

pkong-ds avatar Jul 31 '23 02:07 pkong-ds

Hey all, I also came across the Type 'true' is not assignable to type 'false' error and noticed that Combobox doesn't like React's setState type (e.g., React.Dispatch<React.SetStateAction<string[]>>), but it's fine if you pass a basic function (e.g., (event: string[]) => void).

Example

import { useState } from "react";
import "./App.css";
import { Combobox } from "@headlessui/react";

function App() {
  const [selectedProfiles, setSelectedProfiles] = useState<string[]>(["hello"]);

  return (
    <Combobox
      value={selectedProfiles}
      // ❌ Doesn't work
      // onChange={setSelectedProfiles}

      // ✅ Works
      onChange={(event) => setSelectedProfiles(event)}
      multiple
    >
      <div className="relative">hello world</div>
    </Combobox>
  );
}

export default App;

Hope that helps!

adriancarriger avatar Aug 17 '23 23:08 adriancarriger

@adriancarriger This is a problem with Typescript inference trying to infer related types from the arguments of functions. It's picking up the function that can be passed to setState functions and treating that as one of the possible types in value which further breaks inference. Unfortunately, we have little to no control over where and how TS infers things and in this case it sees the union of the parameters and one of them is a function which is why it breaks.

thecrypticace avatar Sep 01 '23 15:09 thecrypticace

@thecrypticace "it's their problem" is not an answer. if you know what's wrong on the typescript side, could you please open an issue on their repo and link it here?

szamanr avatar Sep 01 '23 15:09 szamanr

@szamanr There is no issue to open and nothing wrong on TypeScript's side here. In fact, I never said what TypeScript was doing is wrong. I said in not so many words that the problem and unexpected results that they were seeing are a result of inference. And, as far as I know, where TypeScript itself is concerned, it's working exactly as designed. For the most part, TS generally infers a generic type from all uses of that generic where possible. Having said that, we may be able to work around it but do not yet know.

thecrypticace avatar Sep 01 '23 16:09 thecrypticace

Hey all, I also came across the Type 'true' is not assignable to type 'false' error and noticed that Combobox doesn't like React's setState type (e.g., React.Dispatch<React.SetStateAction<string[]>>), but it's fine if you pass a basic function (e.g., (event: string[]) => void).

Example

import { useState } from "react";
import "./App.css";
import { Combobox } from "@headlessui/react";

function App() {
  const [selectedProfiles, setSelectedProfiles] = useState<string[]>(["hello"]);

  return (
    <Combobox
      value={selectedProfiles}
      // ❌ Doesn't work
      // onChange={setSelectedProfiles}

      // ✅ Works
      onChange={(event) => setSelectedProfiles(event)}
      multiple
    >
      <div className="relative">hello world</div>
    </Combobox>
  );
}

export default App;

Hope that helps!

Thanks @adriancarriger , That works well.

hc0503 avatar Sep 21 '23 07:09 hc0503

Hey, so here's an example of a reusable multi-select that uses Combobox:

function MultiSelect<TValue extends { id: any }>(props: {
  value: TValue[]
  options: TValue[]
  onChange: (value: TValue[]) => void
  renderButton: () => React.ReactNode
  renderOption: (option: TValue) => React.ReactNode
}) {
  return (
    <Combobox value={props.value} multiple onChange={props.onChange}>
      <Combobox.Input />
      <Combobox.Button>{props.renderButton()}</Combobox.Button>
      <Combobox.Options className="rounded-md border bg-white p-3">
        {props.options.map((option) => (
          <Combobox.Option key={option.id} value={option}>
            {props.renderOption(option)}
          </Combobox.Option>
        ))}
      </Combobox.Options>
    </Combobox>
  )
}

Which can be used in a parent component like so:

<MultiSelect
  value={selectedPeople}
  onChange={(people) => setSelectedPeople(people)}
  options={people}
  renderButton={() => 'Select a person…'}
  renderOption={(person) => person.name}
/>

Notably, I'm wrapping the entirety of Combobox in my own API. This lets Combobox handle anything related to its props without that leaking out of your component. The component itself is still generic because it needs to handle multiple types of data but this is a (very) rough approximation of how I would design a reusable component that utilizes Combobox today. Though, I'd probably experiment around with different styles for the render props and what not. Note that I would also have separate components for Select vs MultiSelect. The reason is that it can signficiantly complicate the generic types if you don't.

If you want to write a wrapper component around Combobox that otherwise works the same way it must be generic in the same way that Combobox itself is. But I would suggest writing wrapper components if you don't want to write/repeat them using the <Combobox>-based API directly as they'll be much easier to write and deal with.

If you're set on writing wrapper components around each of the Combobox components then you can look at a (very short) example of this with regards to generics in my response here: https://github.com/tailwindlabs/headlessui/issues/2773#issuecomment-1745155496

Hope that helps. ✨

thecrypticace avatar Oct 03 '23 15:10 thecrypticace

Hey, so here's an example of a reusable multi-select that uses Combobox:

function MultiSelect<TValue extends { id: any }>(props: {
  value: TValue[]
  options: TValue[]
  onChange: (value: TValue[]) => void
  renderButton: () => React.ReactNode
  renderOption: (option: TValue) => React.ReactNode
}) {
  return (
    <Combobox value={props.value} multiple onChange={props.onChange}>
      <Combobox.Input />
      <Combobox.Button>{props.renderButton()}</Combobox.Button>
      <Combobox.Options className="rounded-md border bg-white p-3">
        {props.options.map((option) => (
          <Combobox.Option key={option.id} value={option}>
            {props.renderOption(option)}
          </Combobox.Option>
        ))}
      </Combobox.Options>
    </Combobox>
  )
}

Which can be used in a parent component like so:

<MultiSelect
  value={selectedPeople}
  onChange={(people) => setSelectedPeople(people)}
  options={people}
  renderButton={() => 'Select a person…'}
  renderOption={(person) => person.name}
/>

Notably, I'm wrapping the entirety of Combobox in my own API. This lets Combobox handle anything related to its props without that leaking out of your component. The component itself is still generic because it needs to handle multiple types of data but this is a (very) rough approximation of how I would design a reusable component that utilizes Combobox today. Though, I'd probably experiment around with different styles for the render props and what not. Note that I would also have separate components for Select vs MultiSelect. The reason is that it can signficiantly complicate the generic types if you don't.

If you want to write a wrapper component around Combobox that otherwise works the same way it must be generic in the same way that Combobox itself is. But I would suggest writing wrapper components if you don't want to write/repeat them using the <Combobox>-based API directly as they'll be much easier to write and deal with.

If you're set on writing wrapper components around each of the Combobox components then you can look at a (very short) example of this with regards to generics in my response here: #2773 (comment)

Hope that helps. ✨

Thanks for the example. The problem seems to return if you add a comparator "by" which is quite important in autocompletes because value can be out of sync with options loaded from remote source.

li4man0v avatar Dec 21 '23 16:12 li4man0v