material-ui: [material-ui][Autocomplete] Component with `freeSolo` and `isOptionEqualToValue` doesn't use string for type of value

Duplicates

  • I have searched the existing issues

Latest version

  • I have tested the latest version

Steps to reproduce 🕹

Link to live example: https://codesandbox.io/s/jolly-sid-x28zcd?file=/src/App.tsx

Steps:

  1. Type something into the input
  2. Press enter
  3. Click on the input again

Current behavior 😯

Page crashes because of error Cannot read properties of undefined (reading 'id')

Expected behavior 🤔

Typescript tells me that value in isOptionEqualToValue could be a string

Context 🔦

I have a similar example to this in my project with a nested object, and just discovered it was crashing because I don’t check if the value is a string. onChange seems to use the correct types of S | string.

Your environment 🌎

Using the mui template codesandbox, which is a browser sandbox not cloud one.

About this issue

  • Original URL
  • State: open
  • Created a year ago
  • Comments: 21 (12 by maintainers)

Most upvoted comments

Maybe this

  isOptionEqualToValue?: (option: Value, value: Value) => boolean;

needs to become

  isOptionEqualToValue?: (option: Value, value: AutocompleteValue<Value, Multiple, DisableClearable, FreeSolo>) => boolean;

Is it a breaking change to start telling the user about a bug in their code when we were previously silent about it? Any code that fails to type check after this change was already broken to begin with, right?

@joshuakb2 You’re right, and I’m okay with implementing this change. I pointed out that it might cause inconvenience to users, but I think the final decision should also be made by other MUI team members and come to an agreement, as it could necessitate users updating their code especially for minor or patch release, even if it was incorrect before. Maybe we could release this in a minor version.

@newsiberian, go ahead and submit your changes in the pull request. We’ll check if all tests pass. If you haven’t already, please add new TypeScript tests. Thanks.

@WillSmithTE But why do you need to use isOptionEqualToValue prop when the Autocomplete is freeSolo?

In my case, the option type is an object so we need isOptionEqualToValue to judge whether the value the user has typed matches the unique ID of an existing option. But we still want to allow the user to type a new value themselves, and when they press enter we open a dialog to help them finish creating the new option.

@WillSmithTE The value type in isOptionEqualToValue should be Value | AutocompleteFreeSoloValueMapping<FreeSolo>, similarly to what’s in getOptionLabel. Would you like to open a PR?

EDIT: Actually, there is a PR that aims to solve this: #37291

You can use Optional Chaining Operator like this, I think this will solve your probelm.

image