代码点读机 / TypeScript / null

null TypeScript · 类型关键字

「故意留空」:程序员主动放进去表示这里没有值,和 undefined(还没赋值)含义不同。

怎么用

let 变量: 类型 | null = null;

小例子

let 头像: string | null = null;
console.log(头像 ?? "默认头像");
头像 = "我.png";
console.log(头像 ?? "默认头像");

运行结果

默认头像
我.png

提醒:用 ?? 或 ?. 处理 null 最安全;typeof null 返回 "object" 是老坑

官方文档:https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← TypeScript全部词条