dohomi/react-hook-form-mui

AutocompleteElement - Can't get typescript typings to work for custom options type

Opened this issue ยท 1 comments

Duplicates

  • I have searched the existing issues

Latest version

  • I have tested the latest version

Current behavior ๐Ÿ˜ฏ

Hi,

Firstly thanks for your hard work on this project!

I'm trying to use the AutocompleteElement with a custom type for the TValue type; and utilising the transform input/output functions to convert to/from the form field type to the custom type. The element I'm trying to create is a country picker; where the API response/form field is the iso3 code i.e. "AUS" and the object passed/rendered by the AutocompleteElement is a custom country object.

Here's the code:

<AutocompleteElement<FieldValues, string, CountryType>
  name={name}
  required
  options={countries}
  transform={{
	  input: (value) => {
		  return getCountryByIso3(value) as AutocompleteValue<
			  CountryType,
			  false,
			  true,
			  false
		  >;
	  },
	  output: (
		  _event: SyntheticEvent,
		  newValue: AutocompleteValue<
			  CountryType,
			  false,
			  true,
			  false
		  >
	  ) => {
		  return newValue.code3;
	  },
  }}
  autocompleteProps={{
	  fullWidth: true,
	  sx: { flexGrow: 1 },
	  size: "small",
	  getOptionLabel: (option: CountryType) => option.name,
	  renderOption: (props, country) => {
		  return (
			  <Box
				  component="li"
				  sx={{ "& > img": { mr: 2, flexShrink: 0 } }}
				  {...props}
			  >
				  <img
					  loading="lazy"
					  width="20"
					  srcSet={`https://flagcdn.com/w40/${country.code.toLowerCase()}.png 2x`}
					  src={`https://flagcdn.com/w20/${country.code.toLowerCase()}.png`}
					  alt=""
				  />
				  {country.name} ({country.code3})
			  </Box>
		  );
	  },
  }}
  {...rest}
  />

Everything is actually working well; the element renders and the input/output functions do their job! However, typescript throws a number of errors on the options, input & output fields:

Screenshot 2024-05-29 092845

The errors are pretty much the same when defining the generic parameters to AutocompleteElement as above, or without..

Any advice on how this is supposed to be typed?

Expected behavior ๐Ÿค”

No response

Steps to reproduce ๐Ÿ•น

Steps:

Hi @jonorogers!, the type returned by transform.input should match the type of the object in the options array. The type casting to Autocomplete<CountryType, false, true, false> in transform.input might be causing the issue.

Could you please set up a CodeSandbox or StackBlitz when you have a chance? This will help us better understand the TypeScript error you're encountering. Thanks so much! ๐Ÿ˜Š