I've been working on converting a JavaScript function to TypeScript, but I keep encountering the error message:
Type 'undefined' cannot be used as an index type
Although I understand that undefined cannot be used as an index, I have tried implementing null checks for the index type and conditional rendering without success.
Below is my code snippet:
useState hook containing values used in the function
const [newUser, setNewUser] = useState({
firstName: "",
lastName: "",
companyName: "",
email: "",
password: "",
id: ""
});
const [errorMessage, setErrorMessage] = useState("");
The function essentially takes the initial newUser values, creates a copy of that object, then utilizes setNewUser to populate the fields entered by the user into the copied newUser object.
const setValues = (propName?: number, value?: any) => {
const cloneUser = { ...newUser };
cloneUser[propName] = value;
setNewUser({ ...cloneUser });
setErrorMessage("");
}
My challenge lies in the fact that cloneUser[propName]
cannot be undefined and used as an index, and at this point, I'm unsure how to work around this issue.