Angular 8 Native Typescript无崩溃,访问器速记 [英] Angular 8 Native Typescript crash-free, accessor shorthand

查看:83
本文介绍了Angular 8 Native Typescript无崩溃,访问器速记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

角度8:

我以前经常用作打字稿方面的技巧:

I used to use as a short hack on typescript side :

object['accessor']['accessor']['accessor']

获得

object.accessor.accessor.accessor

如果其中一个子项为空,则没有抛出错误的风险.

without running the risk of throwing an error if one of the children was empty.

通过今天的ECMA脚本标准在打字稿文件中执行此操作的最佳方法是什么?

What is the best way to do this by today's ECMA Script standards inside the typescript file?

我发现了这个 https://medium.com/inside- rimeto/optional-chaining-in-typescript-622c3121f99b

b/嵌套三元表达式似乎是最好的,但似乎很复杂

the b/ Nested Ternary Expressions seems the best but it seems convoluted

没关系,这会使应用程序崩溃(尽管在组件级别)也一样多.

nevermind, this crashes the application irrecuperably (at the component level, though) just as much.

似乎较新的anguar规则更加严格.他们只是没有提供其他选择.

it seem newer anguar rules are more strict. they just haven't provided an alternative.

推荐答案

我更喜欢布尔表达式方法.

I prefer the boolean expression approach.

let object = {
  accessor: {
    accessor: {
      accessor: "test"
    }
  }
}

if (object
   && object.accessor
   && object.accessor.accessor
   && object.accessor.accessor.accessor) {
  console.log(object.accessor.accessor.accessor);
} else {
  console.log(null);
}

如果您不关心编译时错误检查,则可以执行类似此操作的奇怪操作.我不推荐.

If you don't care about compile time error checking you could do something weird like this. I wouldn't recommend it.

function tryGetValue(obj, propertiesPath) {
  if (!obj) {
    return null;
  }

  if (!propertiesPath) {
    return obj;
  }

  let current = obj;
  let properties = propertiesPath.split(".");
  for (let i = 0; i < properties.length; i++) {
    if (current[properties[i]] !== undefined) {
      current = current[properties[i]];
    } else {
      current = null;
      break;
    }
  }

  if (current !== undefined) {
    return current;
  } else {
    return null;
  }
}

console.log(tryGetValue(object, "accessor.accessor.accessor"));

这篇关于Angular 8 Native Typescript无崩溃,访问器速记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆