I frequently have a collection that might be either undefined or empty. So I write this:
if ((thingies?.length ?? 0) > 0) ...
I guess that's not so bad in the grand scheme, but it ain't pretty. What I really want is a Bash-like operator that means "this variable exists, is an array, and has at least one element":
if (thingies#) ... // it's safe to access thingies[0]
Pretty sure that's not a thing. But what's the most concise Typescript expression of this?
CodePudding user response:
Considering that both undefined
and 0
are falsy values, you can just write:
if (array?.length)
Either array
is undefined
and this will return false
, or it is defined and it will return false
if length === 0
.
CodePudding user response:
I would simply write it like this:
if (Array.isArray(thingies) && thingies.length > 0) {
[...]
}
Not the shortest way but way more clear (and more correct) in my opinion.
Edit:
If it feels too long and you need it often, you can also simply define it as a function:
import {isNonEmptyArray} from "./utils";
if (isNonEmptyArray(thingies)) {
[...]
}
// utils.ts
export const isNonEmptyArray = (array: unknown): array is unknown[] => (
Array.isArray(array) && array.length > 0
)