Typescript 中的 Nullcheck 子链

Nullcheck Children Chain in Typescript

使用严格的 null 检查很好,但它也会导致这种愚蠢:

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

有没有办法在不重复的情况下进行空值检查?

谢谢!

处理此类情况的一种常见方法是使用像 Maybe(有时称为 Option)这样的抽象。使用示例:

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);

作为替代方案,人们可​​能会使用更简洁的内容,例如 dlv

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

尽管由于其紧凑的性质,它可能看起来更有吸引力,但此解决方案永远不可能是类型安全的。表示为字符串的路径无法根据 input 的实际结构进行检查,因此需要类型断言。