JavaScript / TypeScript 中 `null` 与 `undefined` 使用规范
JavaScript / TypeScript 中 `null` 与 `undefined` 使用规范
一、目的
为了提升代码一致性、可读性和可维护性,统一团队中 null 和 undefined 的使用场景与规则,避免混乱与隐患。
二、概念区分
| 类型 | 含义 | 说明 || — | — | — || undefined | 系统默认的“未赋值”状态 | 通常由 JavaScript 引擎自动赋值 || null | 明确表示“空”或“无值” | 由程序员主动赋值,表达“空”或“无效”状态 |
三、使用规范
1. 变量初始化
- 使用 null 初始化非基本类型变量(对象、数组、引用):
ini
1
2
let user: User | null = null;
let items: Item[] | null = null;
csharp
1
2
3
interface Profile {
avatarUrl: string | null;
}
1
2
3
4
function findUser(id: number): User | null {
return users[id] ?? null;
}
- 函数可选参数应使用 ? 来声明,而非 | undefined:
php
1
2
3
4
5
6
7
function greet(name?: string) {
const realName = name ?? 'Guest';
}
### 4. 判断空值
- 判断变量是否为“空”时,使用宽松等于 == null:
ini
1
2
3
4
5
if (value == null) {
// 相当于 value === null || value === undefined
}
- 避免使用 typeof value === 'undefined',除非在处理全局变量或 window 属性。
### 5. 清除引用(优化垃圾回收)
- 使用 null 显式清除引用,有助于垃圾回收:
ini
1
2
3
largeObject = null;
- 不推荐使用 delete obj.prop,可使用 obj.prop = null。
## 四、禁止示例
以下写法不符合规范:
1
2
3
4
5
6
7
8
9
// 不推荐
let data = undefined;
obj.value = undefined;
return undefined;
// 推荐
let data: SomeType | null = null;
obj.value = null;
return null;
五、TypeScript 类型声明建议
对于可能缺省的变量或返回值,使用 null 明确标注:
csharp
1
2
let token: string | null = null;
- 函数参数若为可选项,应使用 ? 而非 | undefined:
1
2
3
function load(id?: number) { ... }
## 六、配套 ESLint 规则建议(可选)
1
2
3
4
5
6
7
{
"rules": {
"no-undefined": "error", // 禁止手动使用 undefined
"@typescript-eslint/strict-boolean-expressions": "warn",
"@typescript-eslint/no-unnecessary-condition": "warn"
}
}
七、总结原则
程序员主动赋值请使用 null。- 系统默认缺省状态使用 undefined,无需手动赋值。- 清除对象引用时使用 null,有助于垃圾回收。- 判断空值时使用 == null,可同时判断 null 和 undefined。- 类型声明中建议优先使用 null,参数可选用 ?。
本文由作者按照 CC BY 4.0 进行授权