原文2017年7月发布并于2017年9月更新strictnullcheck(严格的null检查)json
strictnullcheck
TypeScript编译器标志吗?空指针是最多见的bug之一,而经过strictnullcheck
TypeScript编译器标志能够在很大程度上避免空指针。由于strictnullcheck
标志在TypeScript 2时添加的,因此它的使用尚未那么普遍。截至2017年9月,Angular项目和typeORM项目中使用了该标志,而VSCode、RxJS、ionor或Babylon.js都没有使用该标志。此外,新建一个TypeScript项目时strictnullcheck
并不默认开启,以保证向后兼容,并保持TypeScript是JavaScript的超集。安全
若是你准备编写一个新TypeScript项目,或者有时间将strictnullcheck标志引入到现有的项目中,我建议你这样作。你的应用会所以具有更高的安全性,使用严格的null检查也不会打乱代码,因应用程序本应包含这些检查。缺点是新开发人员还须要学习一个概念。对我来讲,利大于弊,因此我建议打开严格的空检查。学习
严格的空检查的一个例子是:es5
tsconfig.json指针
{ "compilerOptions": { "module": "commonjs", "target": "es5", "noImplicitAny": true, "strictNullChecks": true, "outDir": "./dist" }, "include": [ "src/**/*" ] }
src/user.tscode
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依旧会报此错) }
如上所述:ip