typescript - 检查对象的属性在 Typescript 中是否为空

标签 typescript

在 Typescript 中,我检查对象的属性是否为空,如下所示:

var addressCountryName = response.address == null 
   ? null 
   : response.address.country == null ? null : response.address.country.name;

地址和国家都可以为空...我也试过:

var addressCountryName = response.address?.country?.name;

这似乎行不通......

是否有检查 null/undefined 的最短方法?

最佳答案

目前没有null coalescing operator在 JavaScript 中。有不同的方法来解决它(比如嵌套的三元类型)。如果您愿意将辅助类型和函数推送到某个库中,您可以这样做:

type MyResponse = {
  address?: null | {
    country?: null | {
      name?: null | string
    }
  }
}

let response: MyResponse = Math.random() < 0.5 ? 
  { address: { country: { name: "France" } } } : { address: null }

var addressCountryName = nullSafe(response, r => r.address.country.name); 
// string | undefined | null

nullSafe() 定义如下:

interface NullSigil {
  [k: string]: NullSigil;
}

// phantom property to recover T from NullSafe<T>
type OriginalTypeKey = "***originalType***"

type IsNullable<T, Y, N> = null extends T ? Y :
  undefined extends T ? Y : N;

type NullSafe<T, N = NullSigil> = Record<OriginalTypeKey, T> & (
  T extends object ? {
    [K in keyof T]-?: NullSafe<T[K], N>
  } : IsNullable<T, NonNullable<T> | N, T>
)

type NullUnsafe<T> =
  T extends Record<OriginalTypeKey, infer U> ? U :
  T extends NullSigil ? null :
  T

function nullSafe<T, U>(
  val: T,
  fn: <N extends NullSigil>(nullSafeVal: NullSafe<T, N>) => U
): NullUnsafe<U>;
function nullSafe(val: any, fn: (nullSafeVal: any) => any): any {

  const nullSigil: NullSigil = new Proxy({} as NullSigil, { get(t, p, r) { return r } });
  const deproxify = Symbol("deproxify");

  function ns<T>(obj: T): NullSafe<T>;
  function ns(obj: any) {
    if ((typeof obj === "undefined") || (obj === null)) return nullSigil;
    if (typeof obj !== "object") return obj;
    return new Proxy(obj, { get(t, p, r) { return (p === deproxify) ? t : (p in t) ? ns(t[p]) : nullSigil } });
  }

  const ret: any = fn(ns(val));

  if (ret === nullSigil) return null;
  if (typeof ret !== "object") return ret;
  return ret[deproxify];
}

是的,一团糟,这就是为什么我说要把它塞进图书馆。它通过制作 Proxy 来工作它始终允许您深入了解属性,即使它本质上是空的。

无论如何,这是一种选择。祝你好运!

关于typescript - 检查对象的属性在 Typescript 中是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54354340/

相关文章:

javascript - ngbNav bootstrap Angular 选项卡的路由设置

php - 如何使用 PHP API 和 AngularJS 2 服务正确处理/获取正确的 JSON 响应?

Travis 构建中的 typescript 失败

angular - 反跳异步验证器

typescript - 在 TypeScript 参数签名中处理潜在的空参数

javascript - 优化用 TypeScript 编写的文件内容解析器类

javascript - 在哪里放置谷歌标签管理器标签片段在 Angular 中?

typescript - 如何在使用 Animated.View 的 native react 中为扩展/折叠文本预览设置动画

typescript - 我怎样才能做一个 Partial<Foo> 的类型,但传递的引用仅包含来自 Foo 的键

javascript - Angular 传递标签名称