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的资料请关注代码网其它相关文章!
发表评论