P
P
Peter Sergeev2022-03-29 19:13:00
typescript
Peter Sergeev, 2022-03-29 19:13:00

Why does the "Object is possibly 'undefined'" error occur when looking up an object in an array and reading its property?

recordT interface

export interface record {
  amount?: number,
  categoryId?: string,
  categoryName?: string,
  date?: string,
  description?: string,
  id?: string,
  type?: string
}


CategoriesInterface
export interface CategoriesInterface {
  limit: number,
  title: string,
  id: string
}


CODE
The error occurs in the line
"categoryName: categories.value.find((c: CategoriesInterface) => c.id === record.categoryId).title,"
However, without .title at the end everything works, but when you try to get the property object by key title, then ts throws an error that looks like this:
Object is possibly 'undefined'.

export default defineComponent({
  setup() {
      const records = ref<recordT[]>([])
      const categories = ref<CategoriesInterface[]>([])

      setuPagination(records.value.map((record: recordT) => {
        return {
          ...record,
          categoryName: categories.value.find((c: CategoriesInterface) => c.id === record.categoryId).title,
          typeClass: record.type === 'income' ? 'green' : 'red',
          typeText: record.type === 'income' ? 'Доход' : 'Расход'
        }
      }))
  }
})


IF replaced like this, then everything also works and .title no longer swears
******
    const categories = ref<any>([])
******

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
wonderingpeanut, 2022-03-29
@223606322

How does the find method work? Finds an element if it exists in the array. If it doesn't exist, it returns undefined.
Typescript doesn't know if the array contains the element you're looking for, so it suggests that you might be trying to get the title property of undefined.
One solution is optional chaining - add a question mark before .title
Another solution:

...
const category = categories.value.find((c: CategoriesInterface) => c.id === record.categoryId);
...
return {
  ...
  categoryName: category ? category.title : 'default name'
  ...
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question