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:
- Type something into the input
- Press enter
- 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)
Maybe this
needs to become
@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.
In my case, the option type is an object so we need
isOptionEqualToValueto 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
valuetype inisOptionEqualToValueshould beValue | AutocompleteFreeSoloValueMapping<FreeSolo>, similarly to what’s ingetOptionLabel.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.