I need to sort an array of objects on an optional integer property order
in the interval [0, n]. I'm using the JavaScript Array.prototype.sort() for this.
Since order
is optional, I know that in my sort I have to confirm that the property exists on the two comparing objects. But since order
may equal 0 ( which is falsy), I can't check by the conditional clause (a.order && b.order)
- which is sufficient to make TypeScript not complain.
I thought that I could use (a.hasOwnProperty('order') && b.hasOwnProperty('order')
, but when I try that conditional clause, TypeScript is complaining that Object is possible undefined. ts(2532)
.
So somehow hasOwnProperty
isn't sufficient to make TypeScript believe that the property actually exists.
At the end of the day, the need is really: How do I sort an array of object by an optional numeric field whose set of possible values may (actually - will) include 0.
But the question at hand is:
How do I make TypeScript understand that two objects do have the necessary property for comparison, if I can't use a.property && b.property
because either a.property or b.property may be an existing, falsy value (namely, 0).
Edit to add:
The condition (a.order >= 0 && b.order >= 0)
doesn't work for the same reason.
CodePudding user response:
You have a few options to work with your items in your sorting function:
Use undefined type guard
if (a.order !== undefined && b.order !== undefined) {
}
Use typeof type guard
if (typeof a.order === 'number' && typeof b.order === 'number') {
}
Use a default order value if it does not exist
const aSortOrder = a.order ?? DefaultValue
See Advanced Types > Optional parameters and properties
Note that hasOwnProperty
is not implemented to work as a type guard