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;
};
CodePudding user response:
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()
CodePudding user response:
Just don't make items
optional:
const [userList, setUserList] = useState<{
error?: any;
isLoaded: boolean;
items: Object[];
}>({ //...
CodePudding user response:
Since you specified the type of items as optional Object, Typescript shows this error. In most cases, the value of array is not undefined. It may be empty array ([]) or array of items. So If userList cannot hold undefined for array, you may use that value without optional operator. If you are sure that this state variable will hold array value optionally, then try using optional chaining in typescript. Also do the same for user object as well. Since you added all the property of user object as optional
{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>
))}