Home > Mobile >  Typescript: How to pass array element
Typescript: How to pass array element

Time:09-19

In my project, I am trying to insert multiple values ​​at the same time through a text field. Added items and setItems for that. But now there is an error " TS2345: Argument of type '(i: string) => any[]' cannot be assigned to parameter of type 'string[]'". I'm a beginner in react typescript, so any corrections when passing items? Please give me some suggestions to fix this problem.

email.tsx

const Email = (props: Props) => {
  const [items, setItem] = useState<string[]>([]);
...
...
 <EmailChip
            placeholder="Enter Email Addresses"
            LabelName="Enter Email Addresses"
            className="textfield"
            tooltip="true"
            upload
            items={items}
            setItem={setItem}
          />

emailpage.tsx

type Props = {
  ...
  items?: string | any;
  setItem: (items: string[]) => void;
  ...
  const handlePaste = (evt: any) => {
    evt.preventDefault();

    const paste = evt.clipboardData.getData("text");
    const emails = paste.match(/[\w\d\\.-] @[\w\d\\.-] \.[\w\d\\.-] /g);

    if (emails) {
      const toBeAdded = emails.filter((email: any) => !isInList(email));

      

      setItem((i: string) => [...i, ...toBeAdded]);
      console.log("items after", items);
    }
  };
  ...

};

error

enter image description here

CodePudding user response:

You probably wanted to declare setItem as:

setItem: React.Dispatch<React.SetStateAction<string[]>>

And use it like this:

setItem((i: string[]) => [...i, ...toBeAdded])
  • Related