How I can type .map iterations? Typescript show 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.
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()
