Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type '(Person | undefined)[]' is not assignable to type 'People'

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading