Answer the question
In order to leave comments, you need to log in
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
}
export interface CategoriesInterface {
limit: number,
title: string,
id: string
}
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' ? 'Доход' : 'Расход'
}
}))
}
})
******
const categories = ref<any>([])
******
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question