第97章 严格模式下的空值检查
案例97:严格模式下的空值检查——安全读取用户配置
本案例演示在
strictNullChecks 开启时,如何安全处理可能为 null / undefined 的数据。我们将构建一个用户配置读取函数,避免运行时“空引用”错误。
设计思路
定义一个 UserConfig 接口,其中可选字段为 string | undefined。通过类型守卫与可选链操作符,安全获取嵌套属性,并在缺失时提供默认值。
核心代码
interface UserConfig {
name: string;
preferences?: {
theme?: 'dark' | 'light';
fontSize?: number;
};
}
function getTheme(config: UserConfig): string {
// 可选链 + nullish 合并,返回安全默认值
return config.preferences?.theme ?? 'light';
}
function printConfig(config: UserConfig): void {
console.log(`用户: ${config.name}`);
console.log(`主题: ${getTheme(config)}`);
// 类型守卫:确保preferences存在再访问fontSize
if (config.preferences) {
console.log(`字号: ${config.preferences.fontSize ?? 16}px`);
} else {
console.log('字号: 未设置,使用默认值 16px');
}
}
// 测试
const config1: UserConfig = { name: '张三' };
const config2: UserConfig = {
name: '李四',
preferences: { theme: 'dark', fontSize: 14 }
};
printConfig(config1);
printConfig(config2);
运行方法:将代码保存为
strict-null.ts,执行 tsc strict-null.ts --strictNullChecks --target es2020 编译后用 node strict-null.js 运行。
预期输出:
用户: 张三
主题: light
字号: 未设置,使用默认值 16px
用户: 李四
主题: dark
字号: 14px
用户: 张三
主题: light
字号: 未设置,使用默认值 16px
用户: 李四
主题: dark
字号: 14px
注意:若未开启
strictNullChecks,config.preferences?.theme 的 undefined 会被静默传递,不会报错但易产生隐藏bug。开启后编译器会强制你处理 null/undefined,建议生产环境始终开启。
测试建议
尝试手动将 config2.preferences 设为 null,观察编译器是否报类型错误(严格模式下不允许)。还可以使用 !. 非空断言故意绕过检查,观察运行时行为差异。