I am getting this typescript error when returning updated state from reducer:
Type ‘(Person | undefined)[]’ is not assignable to type ‘People’
reducer.ts:
export type Person = {
id: string;
name: string;
phone: number;
email: string;
hobbies: string[];
};
export type People = Array<Person>;
type State = { people: People; modal: null | string };
type Action = {
type: string;
obj?: Person;
data?: { id: string; obj: Person };
};
const initState: State = { people: [], modal: null };
export const reducer = (state: State = initState, action: Action): State => {
if (action.type === "ADD") {
let newPeople = [...state.people, action?.obj];
return { ...state, people: newPeople };
}
return state
}
actions.ts:
import { Person } from "../reducers/reducer";
import { AppDispatch } from "../store";
export const add = (obj: {}) => (dispatch: AppDispatch) => {
dispatch({ type: "ADD", obj });
};
I am trying to update the state in reducer but i am not able to assign people to new People and I am getting these errors:
Type '(Person | undefined)[]' is not assignable to type 'People'.
Type 'Person | undefined' is not assignable to type 'Person'.
Type 'undefined' is not assignable to type 'Person'.ts(2322)
reducer.ts(10, 16): The expected type comes from property 'people' which is declared here on type 'State'
>Solution :
The issue is on this line
let newPeople = [...state.people, action?.obj];
due to the optional chaining action?.obj may be undefined. One fix could be something like
let newPeople = state.people;
if (action.obj !== undefined) {
newPeople.push(action.obj);
}