skip to Main Content

I have below ReactJS use hook from Autocomplete field, using Typescript version 4.9.5.

VS code editor giving error in options={products} line. looking some help to fix this error message.

code URL:
https://codesandbox.io/s/happy-bhabha-uhti49?file=/src/CarAutoComplete.tsx:1697-1718

<Controller
          control={methods.control}
          name={"selectedProducts"}
          render={({ field: { onChange, value } }) => (
            <Autocomplete
              multiple
              id="product-selection"
              options={products}
              getOptionLabel={(product) => product.name}
              renderInput={(params) => (
                <TextField
                  {...params}
                  variant="standard"
                  label="Select a Product"
                  placeholder="Type to filter list"
                />
              )}
              onChange={(_, data) => {
                onChange(data);
                return data;
              }}
              defaultValue={initFormFieldValues.selectedProducts}
            />
          )}
        />

Error message

(property) UseAutocompleteProps<never[], true, false, false>.options:
readonly never[][] Array of options.

Type ‘Product[]’ is not assignable to type ‘readonly never[][]’.
Type ‘Product’ is missing the following properties from type ‘never[]’: length, pop, > > push, concat, and 29 more.ts(2322)

full code:

import { useState, useEffect } from "react";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
import { Select, MenuItem, Autocomplete } from "@mui/material";
import { useForm, SubmitHandler, Controller } from "react-hook-form";

export interface Product {
  id: number;
  name: string;
}

export interface FormFields {
  invoiceNumber: number;
  selectedProducts: Array<Product>;
}

export default function CarAutoComplete() {
  const [products, setProducts] = useState<Array<Product>>([
    { id: 1, name: "Mouse" },
    { id: 2, name: "Printer" },
    { id: 3, name: "Monitor" },
    { id: 4, name: "server" }
  ]);

  const initFormFieldValues = {
    invoiceNumber: 0,
    selectedProducts: []
  };

  const methods = useForm<FormFields>({
    defaultValues: initFormFieldValues
  });

  const onSubmit = (data: FormFields) => alert(JSON.stringify(data));

  return (
    <div style={{ width: "400px", margin: "20px" }}>
      <form onSubmit={methods.handleSubmit(onSubmit)}>
        <Controller
          control={methods.control}
          name={"invoiceNumber"}
          render={({ field: { onChange, value } }) => (
            <TextField
              variant="standard"
              style={{ margin: "5px" }}
              onChange={onChange}
              value={value}
              placeholder="Invoice Number"
              type="number"
            />
          )}
        />
        <br />

        <Controller
          control={methods.control}
          name={"selectedProducts"}
          render={({ field: { onChange, value } }) => (
            <Autocomplete
              multiple
              id="product-selection"
              options={products}
              getOptionLabel={(product) => product.name}
              renderInput={(params) => (
                <TextField
                  {...params}
                  variant="standard"
                  label="Select a Product"
                  placeholder="Type to filter list"
                />
              )}
              onChange={(_, data) => {
                onChange(data);
                return data;
              }}
              defaultValue={initFormFieldValues.selectedProducts}
            />
          )}
        />

        <Button variant="contained" style={{ margin: "5px" }} type="submit">
          Send
        </Button>
      </form>
    </div>
  );
}

2

Answers


  1. This means that your defaultValue that is provided is not is not contained within the supplied options.

    Providing one of the options as your default value should clear this up.

    eg.

    const initFormFieldValues = {
      invoiceNumber: 0,
      selectedProducts: [{ id: 1, name: "Mouse" }]
    };
    
    Login or Signup to reply.
  2. The only change needed is to specify the type (FormFields) of initFormFieldValues. Without this, TypeScript infers an undesirable type for initFormFieldValues.selectedProducts and then it thinks that the type of what you provide for the options prop conflicts (with regard to Autocomplete‘s expectations about how they should relate) with the type of what you provide for the defaultValue prop.

      const initFormFieldValues: FormFields = {
        invoiceNumber: 0,
        selectedProducts: []
      };
    

    Edit TypeScript error

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search