简体   繁体   中英

Mui Autocomplete says onChange value can be string

I'm rendering a MUI Autocomplete with my custom type like this:

type Option = { label: string; value: string };
return (
  <MuiAutocomplete<Option, true, any, true>
    freeSolo={true}
    onChange   // says value can be type Option | string
  />
);

However, the onChange signature is saying the type of the value can be Option | string Option | string instead of just Option .

See here: https://codesandbox.io/s/freesolo-demo-material-ui-forked-sn8l5i?file=/demo.tsx

Does anyone know why this is?

You havent defined an onChange function

type Option = { label: string; value: string };
const handleOnChange = (e) => {
  console.log('Changed')
}
return (
  <MuiAutocomplete<Option, true, any, true>
    freeSolo={true}
    onChange={handleOnChange}   // says value can be type Option | string
  />
);

The entire error message in your codesandbox is:

(JSX attribute) UseAutocompleteProps<Option, true, any, true>.onChange?: (event: React.SyntheticEvent<Element, Event>, value: (string | Option)[], reason: AutocompleteChangeReason, details?: AutocompleteChangeDetails<...>) => void Callback fired when the value changes.

@param event — The event source of the callback.

@param value — The new value of the component.

@param reason — One of "createOption", "selectOption", "removeOption", "blur" or "clear".

@param details

Type 'boolean' is not assignable to type '(event: SyntheticEvent<Element, Event>, value: (string | Option)[], reason: AutocompleteChangeReason, details?: AutocompleteChangeDetails<...>) => void'.ts(2322) useAutocomplete.d.ts(267, 3): The expected type comes from property 'onChange' which is declared here on type 'IntrinsicAttributes & AutocompleteProps<Option, true, any, true, "div">'

This says the type must be

(event: SyntheticEvent<Element, Event>, value: (string | Option)[], reason: AutocompleteChangeReason, details?: AutocompleteChangeDetails<...>) => void

That's not even close to the same as Option | string Option | string . Rather, it says that onChange must be a function which takes 3 required arguments and one optional argument and returns void . In fact, in general, any prop that starts with "on" is a callback and must be a function.

One key here is to make sure you understand the entire error message. And when you ask a question, copy/paste the error message instead of typing your own summary. It is easy to miss important details if you don't post the whole thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM