I'm using Sequlize and Typescript. Have to do some raw query to get data (All the Parent Categories of the existing categories) from the PostgreSQL database. as an array of objects. Basically, recursive SELECT statement.
According to the Sequelize manual, the raw query returns two arguments, result
and metadata
(usually a number of affected rows) unless you specify the query type explicitly. In this case, it should return just the result.
So eventually my code looks like this:
const parentCat = await SomeDataModel.sequelize?.query(
getAllParentCategories,
{
replacements: { subcategory_code: ARRAY_OF_CATEGORIES_TO_SEARCH },
type: QueryTypes.SELECT
}
);
According to the Types assigned, it returns parentCat
that type of [undefined, number] | undefined`. Assuming that the first argument in the array is the result.
if I Try to console.log the result it returns an array of objects (as intended):
[
{ category_code: 'Value1' },
{ category_code: 'Value2' },
{ category_code: 'Value3' },
{ category_code: 'Value4' },
{ category_code: 'Value5' }
]
However, if I try to deconstruct this array and use it keep complaining that the object is possibly undefined. Even though I check that array exists, elements are not undefined or null, and the length of the array is more than 0)
And then when I try to access the object's property (e.g: category_code) it keeps complaining that the Property 'category_code' does not exist on type 'number'
. My code is:
if (parentCat !== undefined && parentCat.length > 0) {
const additionalCats = parentCat.reduce<string[]>((acc, currentCategory) => {
return currentCategory ? [...acc, currentCategory.category_code] : acc;
}, [])
console.log(additionalCats);
}
Plus, the ternary operation is redundant here anyway, cause DB either returns an empty array or array of objects with categories in it. Since I already checking for the array not being empty I think it doesn't make a lot of sense. But Typescript keeps complaining otherwise if I try to get rid of it.
Maybe someone can suggest anything to tackle this?
question from:
https://stackoverflow.com/questions/65930260/sequelize-typescript-accessing-results-of-a-raw-query