0

we're all familiar with the

tune?.image

type of null checks in Typescript optional chaining docs

but what's the best practice for checking this with an array value?

tune.images?[0]

will not work. I often use:

tune.images ? tune.images[0] : null

actually I think this is the better example:

tune.images.length

where tune?.images?.length will fail.

the best alternate I've found is:

if (!tune.images || tune?.images?.length < 1) {

but it seems overly verbose. Better ideas?

4
  • 3
    You are missing a dot: tune.images?.[0], see optional chaining with expressions
    – Hao Wu
    Commented Nov 22, 2022 at 6:57
  • 1
    The documentation you linked to mentions how to do this with bracket notation. But this is an ECMAScript feature anyway, so the JavaScript documentation of the real thing is on MDN. Commented Nov 22, 2022 at 6:59
  • i.sstatic.net/md3eC.png
    – VLAZ
    Commented Nov 22, 2022 at 7:04
  • clarified - reading a property like length seems to be the more problematic
    – dcsan
    Commented Dec 2, 2022 at 0:38

0