Search code examples
reactjstypescripttypeerrorreact-props

Is there a better way to work with interfaces and get rid of 'TypeErrors'?


I'm stucked in a TypeError in my ReactJS project. The error:

Server Error:
TypeError: Cannot read properties of undefined (reading 'phoneNumber')
---------------------------------------------------------------------------------------
Source:
~/components/index.tsx (74:28)
> 74 | phoneNumber: props.data.manager.phoneNumber,

The code below is where the compiler claims to have a TypeError.

const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(formSchema),
    defaultValues: defaultValues,
});

interface DataProps {
  id: number;
  accountTypeEnum: string;
  phoneNumber: string;
}
//The function below is inside the main function. I didn't paste the entire code so this question doesn't get too much big
const defaultValues: DataProps = {
    id: props.data.id,
    accountTypeEnum: props.data.accountTypeEnum,
    phoneNumber: props.data.manager.phoneNumber, //here's where the error occurs
  }

So after that i have a form that will be used to change the user's info. Basically the form starts with the defaultValues and so the user can change if he want it.

return(
 <Form>
  <Input
     name="phone"
     type={"text"}
     label="Phone Number"
     error={errors.phoneNumber}
     mask="phone"
     {...register("phone")}
   />
 </Form>
);

When i delete the 74º line the page renders but the info doesn't show. I know that this is happening cause phoneNumber is undefined but i really don't know how to fix that. I'm a newbie into Typescript as you may see. You can click here to see the entire typescript file on Pastebin.


Solution

  • So whenever you see error like this, that normally means anything to the left of the dot right before the phoneNumber is undefined. In this case, it could be your props.data.manager is undefined. Double check if you forgot to pass it down as a prop.