#'result' is possibly 'undefined'
11 messages · Page 1 of 1 (latest)
you need to ask yourself what you want your application to do if a review or user with a particular ID no longer exists in your reviews/users array. do you want it to then exclude that entire result from the output? if so then you can use flatmap to exclude those cases:
Preview:```ts
const reviews = [
{id: 1, userId: 2},
{id: 2, userId: 1},
{id: 3, userId: 7},
{id: 4, userId: 3},
{id: 5, userId: 1},
{id: 6, userId: 6},
{id: 7, userId: 2},
{id: 8, userId: 4},
]
const users = [
{id: 1, name: "Bob"},
{id: 2, name:
...```
` book.reviewIds.reduce((result, reviewId) => {
let resultItem = reviews.find((r) => r.id === reviewId);
if (resultItem) {
const user = users.find((user) => user.id === resultItem.userId);
if (user) {
const reviewInfo: ReviewInfo = {
id: resultItem.id,
user: {
id: user.id,
name: user.name
},
text: resultItem.text
};
result.push(reviewInfo);
}
}
return result;
}, [] as ReviewInfo[]) || []; `
that results in an ugly type of this though:
({
id: number;
user: {
id: number;
name: string;
};
} | null)[]
filter(Boolean) doesn't actually narrow an array to exclude null/undefined on the type level
where's the filter(Boolean) though
They edited