Search code examples
typescriptantd

Where is the type for onSelect's option type in antd Autocomplete?


In our ui library we used antd AutoComplete and we pass onSelect function through. OnSelect accepts 2 args. 1 is a value which is string and the other is option which shows type as OptionData | OptionGroupData

My question is where can I import OptionGroupData and OptionData from? Version of antd:

"antd": "4.23.6"

PS: Module '"rc-select/lib/interface"' has no exported member 'OptionGroupData'.ts(2305)


Solution

  • In the older versions Normally These interfaces were located in

    node_modules/rc-select/lib/interface/index.d.ts
    

    And they were:

    export interface OptionCoreData {
        key?: Key;
        disabled?: boolean;
        value: Key;
        title?: string;
        className?: string;
        style?: React.CSSProperties;
        label?: React.ReactNode;
        /** @deprecated Only works when use `children` as option data */
        children?: React.ReactNode;
    }
    export interface OptionData extends OptionCoreData {
        /** Save for customize data */
        [prop: string]: any;
    }
    export interface OptionGroupData {
        key?: Key;
        label?: React.ReactNode;
        options: OptionData[];
        className?: string;
        style?: React.CSSProperties;
        /** Save for customize data */
        [prop: string]: any;
    }
    

    But in a version like "4.23.6", apparently these interfaces were removed. The second argument type is now:

    {id:number; value:string}
    

    For example you can use AutoComplete:

    const MyAutoComplete: React.FC = () => {
      const [value, setValue] = useState('');
      const [options, setOptions] =
        useState<{ value: string, id: number }[]>([
          { id: 1, value: "firstItem" },
          { id: 2, value: "secondItem" }
        ]);
    
      const onSelected = (value: any, option: { id: number; value: string }) => {
        console.log(value, option);
      };
    
      const onChange = (data: string) => {
        setValue(data);
      };
    
    
      return (
        <AutoComplete
          options={options}
          onSelect={(value, option) => onSelected(value, option)}
        />
      );
    };