Typescript: Autocomplete value validation when using controlled value (empty first) but with disabledClearable on

Open
#29,046 5 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
react, typescript
Domain
frontend

Research direction

Start with @mui/core/AutocompleteUnstyled/useAutocomplete.d.ts and reproduce the TypeScript error in the linked CodeSandbox. Check the AutocompleteValue type against the controlled empty value and disabledClearable case; done means the reported controlled usage type-checks while the existing value constraints remain intact.

Written by the indexing model from the issue text.

Description

scope: autocomplete support: question typescript
  • [ X] The issue is present in the latest release.
  • [ X] I have searched the issues of this repository and believe that this is not a duplicate.

Current Behavior 😯

Im implementing the Autocompleted with controlled state (from react-hook-form).
The Value in the beginning should be emtpy => null
When the user selects an Item the ID of the item is the controlled value.

When providing value || null the typescript compiler throws an error because nullable values are not allowed when disableClearable is set. It makes sence that an updated value cannot be null but initialy it makes sence.

Expected Behavior 🤔

Allow null as value even when disableClearable is set.

Steps to Reproduce 🕹

@mui/core/AutocompleteUnstyled/useAutocomplete.d.ts

export type AutocompleteValue<T, Multiple, DisableClearable, FreeSolo> = Multiple extends
  | undefined
  | false
  ? DisableClearable extends true
    ? NonNullable<T | AutocompleteFreeSoloValueMapping<FreeSolo>>
    : T | null | AutocompleteFreeSoloValueMapping<FreeSolo>
  : Array<T | AutocompleteFreeSoloValueMapping<FreeSolo>>;

https://codesandbox.io/s/combobox-material-demo-forked-dd8de?file=/demo.tsx

Context 🔦

I have a form (react-hook-form) one field is userId which can be selected from a list of users
The value is controlled and should contain the userId directly which is why I dont just pass the whole object (label + id) as value but rather select the option by value (id)

Dominant language
JavaScript
Stars
99.1k
Forks
32.5k
Avg merge
2d 17h
Merged PRs (30d)
106

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from mui/material-ui

All issues in mui/material-ui

Similar issues

More JavaScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.