0

Is there any sugar to ensure that map will not typeerror using tools like optional chaining/nullishcoalescing?

let x = {y: 1, z: 2};

x?.map(i => i); // Typeerror
Array.isArray(x)?.map(i => i); // Typeerror

let y = '1234';
y?.length && y.map(i => i) // Typeerror
Armeen Moon
  • 18,061
  • 35
  • 120
  • 233
  • These type errors seem to be correct. What's the intent here? You obviously can't call map on an object literal, boolean, or string. – Eric Ferreira Feb 08 '20 at 05:42
  • 1
    Yeah Just looking for a terse way to avoid doing `Array.isArray(x) && x.map` – Armeen Moon Feb 08 '20 at 05:44
  • Ah okay! Got it. See if the below helps. – Eric Ferreira Feb 08 '20 at 05:47
  • It's a bit strange (and often indicative of smelly code) to not know whether something is an array or not beforehand IMO. If you ever encounter a situation like this, consider fixing things upstream – CertainPerformance Feb 08 '20 at 06:02
  • 1
    @CertainPerformance Have used Optional Chaining with Nullish Colalescing inside JSX? Switching Components based on union data types Array|number like is pretty common usecase and it gets super elegant with Optional Chaining + Nullish Coalescing. – Armeen Moon Feb 08 '20 at 06:34

1 Answers1

1

These type errors seem to be correct. You obviously can't call map on an object literal, boolean, or string.

If you want to optionally call map anyways, you can continue the optional chaining with ?.(params):


let x = {y: 1, z: 2};

x?.map?.(i => i);
Array.isArray(x)?.map?.(i => i);

let y = '1234';
y?.length && y.map?.(i => i)

Keep in mind this only checks if a property called map exists and is non-null/undefined. If it does exist but isn't a function, you'll still get an error.

Eric Ferreira
  • 1,811
  • 18
  • 20