1

Using strict null checking is great, but it's also resulting in this sort of silliness:

if (x)
  if (x.y)
    if (x.y.z)
      if (x.y.z.stringProperty)
        console.log(x.y.z.stringProperty)

Is there a way to do this null checking without repetition?

Thanks!

calben
  • 1,328
  • 3
  • 18
  • 33

1 Answers1

1

A common way of dealing with such scenarios is by using an abstraction like Maybe (sometimes called Option). Example use:

import { Option } from 'space-lift';

Option(input)
  .map(input => input.x)
  .map(x => x.y)
  .map(y => y.z)
  .map(z => z.stringProperty)
  .forEach(console.log);

As an alternative, one might use something more succinct like dlv.

console.log(dlv(input, ['x.y.z.stringProperty']) as string);

Although it might look more appealing due to its compact nature, this solution can never be type-safe. The path expressed as a string cannot be checked against the actual structure of your input, hence type assertion.

Karol Majewski
  • 23,596
  • 8
  • 44
  • 53
  • 1
    A type-safe version of something like `dlv` is totally possible in TypeScript: https://github.com/Microsoft/TypeScript/issues/12290#issuecomment-456670318 – Curtis Fenner Feb 17 '19 at 03:23
  • Delve looks like an interesting alternative. – calben Feb 17 '19 at 06:32
  • @CurtisFenner Unfortunately, that's not exactly true. That solution breaks when your object has optional properties (which is the case here). The type of `get(input, 'x', 'y', 'z', 'stringProperty')` is inferred to be `never`. – Karol Majewski Feb 17 '19 at 14:38
  • There's also [this possibility](https://stackoverflow.com/a/54354538/2887218) which uses a null-safe proxy of the object in question. – jcalz Feb 17 '19 at 15:19