空 and undefined in TypeScript
Handle 空 and undefined safely 使用 strictNullChecks, union 类型, and definite assignment.
你将学到
- difference 之间空 and undefined in TypeScript
- 如何 strictNullChecks prevents 空-related bugs
- Using union 类型 (T | 空) 到 model absence
- Definite assignment assertion for late-initialized 属性
概念讲解
Two Kinds of Nothing
JavaScript has two empty values: 空 (an intentional absence) and undefined (an uninitialized variable or missing property). TypeScript treats them as distinct types. By default (without strictNullChecks), 空 and undefined are assignable to any type, which is dangerous — you can assign 空 to a 字符串 variable and get a runtime error later. With strictNullChecks enabled, you must explicitly opt into nullability with a union: 字符串 | 空.
strictNullChecks
This is the single most important compiler flag. When enabled, 空 and undefined are not assignable to other types. A variable typed 字符串 cannot hold 空. To allow null, you write 字符串 | 空. This forces you to handle the null case before using the value, eliminating the infamous "cannot 读取属性的空" runtime error. Most modern TypeScript projects enable this flag via strict: 真 in tsconfig.
Definite Assignment
Sometimes a property is initialized after construction (e.g. by a framework or in an init method) but TypeScript cannot see the assignment. The definite assignment assertion (!) tells the compiler "trust me, 这个将是设置": name!: 字符串. Use it sparingly — it bypasses the compiler's check. Prefer initializing in the constructor or using a setter that the compiler can track.
示例代码
// With strictNullChecks, null must be explicit.
let username: string | null = null;
username = "Alice";
// The compiler forces you to handle null before use.
function greet(name: string | null): string {
if (name === null) {
return "Hello, Guest";
}
// name is narrowed to string here.
return "Hello, " + name.toUpperCase();
}
// Definite assignment assertion — initialized later.
class Service {
private client!: string; // Will be set by init()
init(): void {
this.client = "connected";
}
status(): string {
return this.client;
}
}
console.log(greet(null));
console.log(greet("bob"));
const svc = new Service();
svc.init();
console.log(svc.status());
strictNullChecks 制作空 and undefined explicit — 它们 cannot sneak 到 other 类型. Use T | 空到 model absence. definite assignment assertion (!) handles late initialization 但应该是 used sparingly.
动手试一试
- JSON Validator
验证 JSON for 空 and undefined 字段之前处理.
- JSON 到 TypeScript
Generated 类型包含空 unions for nullable JSON 字段.
常见错误
错误写法
禁用 strictNullChecks 到 avoid 空-handling 错误
正确做法
Keep strictNullChecks on. Handle 空 explicitly 使用检查, 默认值, or 可选 chaining. 禁用它 reintroduces 运行时空 错误.
错误写法
Using 非-空 assertion (!) everywhere 相反的 handling 空
正确做法
! 运算符 suppresses 检查不使用验证. Use 它仅 当你 有 proof 值是 非-空. 否则, handle 空情况使用 conditional or 默认.
练习 空 and undefined in TypeScript
1 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。