I am faced with the challenge of sorting an array of objects based on an optional integer property called order
, which falls within the range of [0, n]. To achieve this task, I am utilizing JavaScript's Array.prototype.sort() method.
Given that the presence of the order
property is not guaranteed, I understand that while comparing two objects, I must first ensure that both objects possess this property. However, due to the fact that order
can have a value of 0 (which evaluates to falsy), I cannot simply check for its existence using a conditional statement like (a.order && b.order)
, as this may lead TypeScript to raise an error.
I initially considered using
(a.hasOwnProperty('order') && b.hasOwnProperty('order')
, but doing so resulted in TypeScript warning me about the potential null or undefined values: Object is possible undefined. ts(2532)
.
Therefore, it seems that relying solely on hasOwnProperty
does not convince TypeScript that the property truly exists.
In essence, my main concern boils down to: How can I effectively sort an array of objects by an optional numeric field, where the feasible range includes 0?
However, the specific question at hand remains:
How can I convey to TypeScript that both objects indeed possess the requisite property for comparison, especially when a.property && b.property
may not suffice due to either object's property potentially being present but set to a falsy value such as 0?
An additional point to note is that even the condition
(a.order >= 0 && b.order >= 0)
fails to address the underlying issue for similar reasons.