Home > Software engineering >  Error : Property 'label' does not exist on type 'unknown'.ts(2339) in reactjs
Error : Property 'label' does not exist on type 'unknown'.ts(2339) in reactjs

Time:01-11

I am following below links to create simple example

enter image description here

CodePudding user response:

It seems in the "working" version that all the types are allowed to be inferred because everything is internal to the component. When you create an external component you've not typed the props that are passed to your AutoComplete component. Ideally you'd fully type the HookAutoComplete props object.

Without going down the rabbit hole for how mui-react-hook-form-plus is exporting hooks and any type declarations from react-hook-form it's trivial to just type the isOptionEqualToValue manually.

interface FilmOption {
  label: string;
  year: number;
}

interface Value {
  label: string;
}

export const top100Films: FilmOption[] = [
  { label: "The Shawshank Redemption", year: 1994 },
  { label: "The Godfather", year: 1972 },
  { label: "The Godfather: Part II", year: 1974 },
  { label: "The Dark Knight", year: 2008 },
  { label: "12 Angry Men", year: 1957 },
  { label: "Schindler's List", year: 1993 },
  { label: "Pulp Fiction", year: 1994 }
];

export default function AutoComplete({ registerState }) {
  return (
    <HookAutoComplete
      {...registerState("movie")}
      autocompleteProps={{
        options: top100Films,
        autoHighlight: true,
        isOptionEqualToValue: ({ label }: FilmOption, value: Value) =>
          label === value.label
      }}
      textFieldProps={{
        label: "Movie",
        placeholder: "The..."
      }}
      gridProps={{
        xs: 12
      }}
      rules={{
        required: {
          message: "Required",
          value: true
        }
      }}
    />
  );
}
  • Related