I am having Typescript errors if I try to update nested values of an object. This is my code.
type InterviewType = {
time: string;
person_name: string;
}
type FormState = {
description: string | undefined;
interviews: InteviewType[] | undefined;
};
const [formState, setFormState] = useState<FormState>({
description: '',
interviews: [],
});
useEffect(() => {
setFormState({
...formState,
description: interviewData?.data.description,
interviews: interviewData?.data.interviews,
});
}, [interviewData]);
interviewData might be like this
{
data: {
description: 'Some Description',
interviews: [
{
time: '10:00 AM',
person_name: 'xyz'
},
{
time: '10:10 AM',
person_name: 'xyz2'
},
]
}
}
When I try to update the time with a new value dynamically by the below code, it is giving me an error
setFormState({
...formState,
interviews: {
...formState.interviews,
[index]: {
...formState.interviews[index],
'time': val,
},
},
});
Types of property 'length' are incompatible. Type 'number | undefined' is not assignable to type 'number'. Type 'undefined' is not assignable to type 'number'. TS2322
Now, I can ignore this error by providing ignore ts comment and the code is working fine. But my reviewer didn't accept it and wanted me to remove ignore comments. Any solution or different way to this issue?
setFormState({
...formState,
interviews: {
// @ts-ignore: Object is possibly 'null'.
...formState.interviews,
[index]: {
// @ts-ignore: Object is possibly 'null'.
...formState.interviews[index],
'time': val,
},
},
});
And somehow if I am able to avoid this error by implementing different logic then a new one will come saying Object is possibly 'null' or 'undefined'. TS2533. BTW interviewData is coming from the API. Hence it is obvious that fromState.interviews will be undefined or null initially. So, how can I avoid this error too?
numbertype coming from if you didn't specify (neither implicitly nor explicitly) it anywhere?interviewsshould be an array, right? Your update code try to update it with an objectinterviewsis an array of objects. I have tried to update byinterviews: [in updating formdata but then it is giving more errors in inner code.interviews: { ...formState.interviews, [index]: { ...formState.interviews[index], 'time': val, }, },this looks like object, not array