当前位置: 代码网 > it编程>编程语言>Javascript > TypeScript使用strictnullcheck实战解析

TypeScript使用strictnullcheck实战解析

2024年05月15日 Javascript 我要评论
strictnullcheck(严格的null检查)应该使用strictnullchecktypescript编译器标志吗?空指针是最常见的bug之一,而通过strictnullchecktypesc

strictnullcheck(严格的null检查)

应该使用strictnullcheck typescript编译器标志吗?

空指针是最常见的bug之一,而通过strictnullcheck typescript编译器标志可以在很大程度上避免空指针。因为strictnullcheck标志在typescript 2时添加的,所以它的使用还没有那么广泛。截至2017年9月,angular项目和typeorm项目中使用了该标志,而vscode、rxjs、ionor或babylon.js都没有使用该标志。此外,新建一个typescript项目时strictnullcheck并不默认开启,以保证向后兼容,并保持typescript是javascript的超集。

如果你准备编写一个新typescript项目,或者有时间将strictnullcheck标志引入到现有的项目中,我建议你这样做。你的应用会因此具备更高的安全性,使用严格的null检查也不会打乱代码,因应用程序本应包含这些检查。缺点是新开发人员还需要学习一个概念。对我来说,利大于弊,所以我建议打开严格的空检查。

严格的空检查

严格的空检查的一个例子是:

tsconfig.json

{
  "compileroptions": {
    "module": "commonjs",
    "target": "es5",
    "noimplicitany": true,
    "strictnullchecks": true,
    "outdir": "./dist"
  },
  "include": [
    "src/**/*"
  ]
}

src/user.ts

interface user {
  name: string;
  age?: number;
}
function printuserinfo(user: user) {
  console.log(`${user.name}, ${user.age.tostring()}`)
  // => error ts2532: object is possibly 'undefined'.
  console.log(`${user.name}, ${user.age!.tostring()}`)
  // => ok, you confirm that you're sure user.age is non-null.
  // => 好的,你已经确认user.age是非空的。
  if (user.age != null) {
    console.log(`${user.name}, ${user.age.tostring()}`)
  }
  // => ok, the if-condition checked that user.age is non-null.
    // => 好的,if条件检查了user.age是非空的。
  console.log(user.name + ', ' + user.age != null ? user.age.tostring() : 'age unknown');
  // => unfortunately typescript can't infer that age is non-null here.
  // => 不幸的是typescript不能在这里推断年龄是非空的。(译注:截止至2019年7月16日,ts依旧会报此错)
}

如上所述:

  • 感叹号表示你确信(例如,通过在代码中的某个地方执行检查)可能为空的变量实际上是非空的。
  • 如果执行if条件检查, typescript可以推断某些内容是非空的。
  • 然而,对于三元运算符来说,不幸的是情况并非如此。

翻译自原文:https://www.tsmean.com/articles/learn-typescript/strict-null-checks-best-practice/

以上就是typescript使用strictnullcheck实战解析的详细内容,更多关于typescript使用strictnullcheck的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com