typescript - TypeScript:检查的差异
问题描述
和有什么区别
export function hasValue<T>(val?: T | null): boolean {
return val !== null && val !== undefined;
}
和
export function hasValue<T>(val?: T | null): val is T {
return val !== null && val !== undefined;
}
这里到底是什么意思val is T
?
解决方案
该函数的第二个版本是类型保护。重要的区别是,在类型保护的范围内,值的类型被假定为受保护的类型。在val is T
中,T
是受保护的类型。
例如:
export function hasValue<T>(val?: T | null): val is T {
return val !== null && val !== undefined;
}
var value: int | null; //<-- value has type int | null;
if (hasValue(value)) {
var isPositive = value > 0; //<-- within the scope of the type guard, value has type int
}
else {
//Within this scope, value is null
}
推荐阅读
- sql - 我应该在创建 tsquery 之前从字符串中删除冒号吗?
- c - 在c中的文件中向后退
- sql - SQL - 如何将结果拆分为值总和大致相等的存储桶。非正态分布
- bootstrap-4 - 移动设备上的引导轮播全屏
- javascript - 我的警报有问题,第一个警报正常关闭,但其他警报没有关闭
- swift - 将音节录音修剪到仅元音部分
- netlogo - 如何在 NetLogo 中打开 .tif 文件?
- javascript - 初始化 disabled=True 时按钮 onClick 不起作用(Reactjs)
- android - 使用权限共享首选项
- python - 我正在尝试使用 python 从(https://www.expresslanes.com/map-your-trip) 抓取收费数据,但我不知道如何使用 XHR 抓取数据