编译期非空断言:利用类型守卫消除运行时null检查
通过自定义类型守卫和断言函数,在编译期证明某个值不为null/undefined,且无需运行时断言函数调用。 · 难度:入门 · +10XP
编译期非空断言:利用类型守卫消除运行时null检查
TypeScript 的 ! 非空断言运算符可以消除 null,但它是编译期消除断言,运行时不检查。本教程介绍如何编写自定义类型守卫函数来证明一个值不为 null,并利用 asserts 关键字创建断言函数,这些函数在运行时实际执行检查,同时将类型信息缩小。我们还会探讨通过重载和条件类型创建“编译期证明”模式,减少不必要的运行时分支。
function isDefined<T>(value: T | null | undefined): value is NonNullable<T> {
return value != null;
}
function assertDefined<T>(value: T | null | undefined): asserts value is NonNullable<T> {
if (value == null) throw new Error('Value is null or undefined');
}
const x: string | null = 'hello';
if (isDefined(x)) {
x.toUpperCase(); // 这里x是string
}