Skip to content
Created: October 15, 2020

1. What are null and undefined in TS? ​

In TypeScript:

ts
null; // 一个值,表示“空”
undefined; // 一个值,表示“未定义”

them Both a value and a type :

ts
let a: null = null;
let b: undefined = undefined;

2. Key premise: strictNullChecks ​

Explicitly enable strict checks in new projects:

json
{
  "compilerOptions": {
    "strict": true
  }
}

This includes the following check, but is not equivalent to enabling only this option; strict also enables other strict checks:

json
{
  "strictNullChecks": true
}

The essential difference between on/off ​

❌ Not opened (old project) ​

ts
let s: string;

s = null; // ✅ 不报错
s = undefined; // ✅ 不报错

👉 Extremely dangerous, the type is in name only

✅ With strictNullChecks enabled ​

ts
let s: string;

s = null; // ❌
s = undefined; // ❌

Conclusion:

null and undefined are no longer subtypes of all types

3. Correct use of null / undefined ​

1️⃣ Explicitly declare that it is nullable ​

ts
let s: string | null;
let t: string | undefined;
let u: string | null | undefined;
ts
s = null;
t = undefined;

👉 Must use union type

2️⃣ Optional vs undefined in object properties ​

Optional attribute ? ​

ts
interface User {
  name: string;
  age?: number;
}

Equivalent to:

ts
age: number | undefined;

But not equivalent to null

ts
const u1: User = { name: "Tom" }; // ✅
const u2: User = { name: "Tom", age: 18 }; // ✅
const u3: User = { name: "Tom", age: null }; // ❌

👉 ? = may not exist, not null

3️⃣ undefined in function parameters ​

ts
function foo(x?: number) {}

Equivalent to:

ts
function foo(x: number | undefined) {}
ts
foo();
foo(undefined);
foo(1);

4. The actual usage convention of null vs undefined (very important) ​

🔹 Common conventions in the industry (strongly recommended) ​

ScenarioWhich one to useReason
Variable not initializedundefinedJS native semantics
Parameters optionalundefined? Syntax
Object field missingundefinedJSON convention
Actively "null"nullExplicitly express "null"
The backend returns a null valuenullCommon in databases

Example ​

ts
let currentUser: User | null = null; // 当前无用户

Than

ts
let currentUser: User | undefined;

Semantics are clearer

5. Common pitfalls (must be avoided on the front end) ​

❌ Pitfall 1: Direct access to possibly null values ​

ts
function printLength(s: string | null) {
  console.log(s.length); // ❌
}

✅ Correct way: narrow type (type guard) ​

ts
function printLength(s: string | null) {
  if (s !== null) {
    console.log(s.length); // ✅
  }
}

or:

ts
if (s) {
} // ⚠️ 会排除 '' 0 false

❌ Pit 2: DOM API ​

ts
const el = document.getElementById("app");
el.innerHTML = "hi"; // ❌

✅ Correct writing method ​

ts
const el = document.getElementById("app");

if (el) {
  el.innerHTML = "hi";
}

Or assert (which you're pretty sure exists):

ts
const el = document.getElementById("app")!;

6. ! non-empty assertion (use with caution) ​

ts
el!.innerHTML = "hi";

Meaning:

"I guarantee it is not null / undefined"

⚠️ Won’t check for you at runtime

7. Optional chaining & null value merging (TS + ES2020 artifact) ​

1️⃣ Optional chain ?. ​

ts
user?.profile?.name;

2️⃣ Null value merging ?? ​

ts
const name = user.name ?? "匿名";

Comparison:

ts
||   // 会把 '' 0 false 当成假
??   // 只关心 null / undefined

8. Summarize one sentence (just remember it) ​

TS does not allow you to "pretend null/undefined does not exist"

You must:

  • declare with union type
  • Use judgment to narrow down
  • Use ?. / ??
  • Use ! with caution