嚴格的空檢查

預設情況下,TypeScript 中的所有型別都允許 null

function getId(x: Element) {
  return x.id;
}
getId(null);  // TypeScript does not complain, but this is a runtime error.

TypeScript 2.0 增加了對嚴格空檢查的支援。如果在執行 tsc 時設定 --strictNullChecks(或在 tsconfig.json 中設定此標誌),則型別不再允許 null

function getId(x: Element) {
  return x.id;
}
getId(null);  // error: Argument of type 'null' is not assignable to parameter of type 'Element'.

你必須明確允許 null 值:

function getId(x: Element|null) {
  return x.id;  // error TS2531: Object is possibly 'null'.
}
getId(null);

使用適當的保護,程式碼型別檢查並正確執行:

function getId(x: Element|null) {
  if (x) {
    return x.id;  // In this branch, x's type is Element
  } else {
    return null;  // In this branch, x's type is null.
  }
}
getId(null);