Typescript bracket notation issue in react app

Viewed 87

I need to store and update form input changes, so I added a form state:

const [form, setForm] = useState({
 user: '',
 email: '',
 password: '',
});

I then created a function for handling form changes:

 const handleFormChange = (event: { target: HTMLInputElement | HTMLTextAreaElement }) => {
 const updatedForm: updatedForm = { ...form };
 updatedForm[event.target.name] = event.target.value;
 setForm(updatedForm);
};

I also added an interface for the updatedForm type:

interface updatedForm {
 [key: string]: string;
}

But now there is an error:

Argument of type 'updatedForm' is not assignable to parameter of type 'SetStateAction<{ user: string; email: string; password: string; }>'.

Type 'updatedForm' is missing the following properties from type '{ user: string; email: string; password: string; }': user, email, password

What's wrong, and is there a solution?

1 Answers

Types aren't matching. A possible solution could be to create an interface for the form state (you could also cast it without creating an interface but it wouldn't be very clean):

interface updatedForm {
    [key: string]: string
}

interface IForm {
    user: string
    email: string
    password: string
}

const [form, setForm] = useState<IForm>({
    user: '',
    email: '',
    password: '',
});

const handleFormChange = (event: { target: HTMLInputElement | HTMLTextAreaElement }) => {
    const updatedForm: updatedForm = { ...form };
    updatedForm[event.target.name] = event.target.value;
    setForm(updatedForm as IForm);
};

Or you could also destructure the name and value from target like this and also use destructuring for the setForm assignment:

const handleFormChange = (event: { target: HTMLInputElement | HTMLTextAreaElement }) => {
    const { name, value } = e.currentTarget;
    setForm({ ...form, [name]: value });
};

In this case there would be no need for the updatedForm interface.

Edit: to properly cast the updatedForm type to the IForm type it's necessary to cast them in the following way:

setForm(updatedForm as unknown as IForm)

Because of double assertion

Related