TypeScript最佳實踐:是否使用strictnullcheck

原文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

  1. 感嘆號表示你確信(例如,經過在代碼中的某個地方執行檢查)可能爲空的變量其實是非空的。
  2. 若是執行If條件檢查, TypeScript能夠推斷某些內容是非空的。
  3. 然而,對於三元運算符來講,不幸的是狀況並不是如此。
相關文章
相關標籤/搜索