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?

dcsan
  • 11,333
  • 15
  • 77
  • 118
  • 3
    You are missing a dot: `tune.images?.[0]`, see [optional chaining with expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining#optional_chaining_with_expressions) – Hao Wu Nov 22 '22 at 06: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](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Optional_chaining). – Sebastian Simon Nov 22 '22 at 06:59
  • https://i.stack.imgur.com/md3eC.png – VLAZ Nov 22 '22 at 07:04
  • clarified - reading a property like `length` seems to be the more problematic – dcsan Dec 02 '22 at 00:38

0 Answers0