enum Direction {
North = 'N',
South = 'S',
East = 'E',
West = 'W'
}
function getDirection(str: string): Direction | null {
if (str === 'N' || str === 'S' || str === 'E' || str === 'W') {
return str as Direction;
}
return null;
}
联合类型与类型守卫的协同工作解释
- 联合类型:在函数
getDirection
的返回类型Direction | null
中,|
表示联合类型。它表明函数的返回值要么是Direction
枚举类型中的某一个值,要么是null
。这让函数的返回值可以有多种可能类型。
- 类型守卫:在函数内部,通过
if (str === 'N' || str === 'S' || str === 'E' || str === 'W')
语句进行判断,这就是类型守卫。它基于传入的str
值,在运行时检查str
是否匹配枚举Direction
中的值。如果匹配,通过类型断言str as Direction
将str
转换为Direction
类型返回;如果不匹配则返回null
。类型守卫在运行时缩小了str
的类型范围,使得我们可以在特定分支下安全地将str
当作Direction
类型处理,从而实现联合类型中不同类型的区分处理。