#'result' is possibly 'undefined'

11 messages · Page 1 of 1 (latest)

warm temple
#

i need to get final object like
interface ReviewInformation {
id: string;
user: User;
text: string;
}
where User
interface User {
id: string;
name: string;
}
but method .find may return value or undefined how to handle it

rapid tulip
#
let result = reviews.find((r) => r.id === review) ?? new Review();```
#

try this

obtuse root
#

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:

twilit yachtBOT
#
littlelily#0

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:
...```

sacred dirge
#

` 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[]) || []; `

obtuse root
#

filter(Boolean) doesn't actually narrow an array to exclude null/undefined on the type level

next lake
obtuse root