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

How I can type Array.map iterations?

How I can type .map iterations? Typescript show problem

my problem

{userList.items.map(user => (
<tr className='list_row'>
    <td className='list_col1'> {user.username}</td>
    <td className='list_col2'>{user.email}</td>
    <td className='list_col3'>{user.address}</td>
</tr>
))}

const [userList, setUserList] = useState<{
    error?: any;
    isLoaded: boolean;
    items?: Object[];
  }>({
    error: null,
    isLoaded: false,
    items: [],
  });

I try create type, but don’t understand how use it.

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 User = {
  username?: string | null;
  email?: string | null;
  address?: string | null;
};

>Solution :

If you already have a User type, you can use it like this:
items?: User[]

type User = {
  username?: string | null;
  email?: string | null;
  address?: string | null;
};

const [userList, setUserList] = useState<{
    error?: any;
    isLoaded: boolean;
    items?: User[]; // could be undefined -- User[] | undefined
  }>({
    error: null,
    isLoaded: false,
    items: [],
  });

However, if UserList.items could be undefined or User[], typescript won’t let you call UserList.items.map().

So first you need to check that UserList.items is not undefined before you can map. Otherwise there is a risk of causing a runtime error. eg

userList.items && userList.items.map()

Or with optional chaining syntax eg

userList.items?.map()
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