首页 > 解决方案 > 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

标签: typescript

解决方案


该函数的第二个版本是类型保护。重要的区别是,在类型保护的范围内,值的类型被假定为受保护的类型。在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
}

推荐阅读