0

I have an interface Employee:

export interface Employee {
  firstName: string;
  lastName: string;
}

I am trying to push elements of Type Employee into an array as below:

  let allEmployees: Employee[] = [];
  allEmployees = emp.data?.map((employee) => {
    return { firstName: employee.firstName, lastName: employee.lastName }
  });

I am getting the following typescript compile time error:

type 'undefined' is not assignable to type 'Employee[]'

I have used .map function to return final value of the array. How do I resolve this issue ?

Thanks

2
  • 1
    Please consider editing the code in the question to constitute a minimal reproducible example that can be dropped into a standalone IDE like The TS Playground so others can see the issue for themselves. The type of emp is important here. I presume its data property might itself be undefined, and therefore the optional chaining operator emp.data?.map() will possibly set allEmployees to undefined without ever running map(). Also, I don't see you trying to push any elements; instead you're trying to reassign allEmployees. Do you want to try to push() instead? Commented Jul 29, 2020 at 15:53
  • The push method did work. But I wanted to reuse the .map function. Commented Jul 30, 2020 at 8:21

2 Answers 2

1

? in emp.data? means data is optional and might not exist in emp, which tells typescript not to go through the chained function, i.e map. So your assignment can return undefined or Employee[], which cannot be assigned to allEmployees.

Sign up to request clarification or add additional context in comments.

1 Comment

One of many possible fixes: let allEmployes = (emp.data ?? []).map(/*...*/);
0

It's because emp.data? possibly returns void 0 as well. That's why you don't have to use proposal-optional-chaining, just check like below:

allEmployees = emp.data ? emp.data.map((employee) => {
  return { firstName: employee.firstName, lastName: employee.lastName }
}) : [];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.