How to fix error Object is possibly undefined while accessing data from a map with key value pair?

I have a below list:

const userRolesMap = new Map([
["admin", ["user#1", "user#2"]],
["customer", ["user#3", "user#4"]],
["accounting", ["user#5", "user#6"]]
]);

And, wanted to display these users in user drop down, depending upon user role type.

Now, while rendering it like below, is giving me error Object is possibly 'undefined':

{!(userRolesMap !== undefined && userRolesMap.size > 0) ? null :
  userRolesMap.get("admin").map((user, index) => (
  <option key={index} value={user}>{user}</option>
))}

Also, tried Object.entries approach but that is also not resolving this error. What am I missing in my approach?

>Solution :

I might be wrong, or you pasted your code wrong, but it looks like you have a typo. You’re using userRoleMap instead of userRolesMap (missing the s). It also looks like you’re using TS so you can use the optional chaining operator.

{!(userRolesMap !== undefined && userRolesMap.size > 0) ? null :
  userRolesMap.get("admin")?.map((user, index) => (
  <option key={index} value={user}>{user}</option>
))}

Leave a Reply