概述
- 在 TypeScript 中,
is
关键字主要用于类型守卫(Type Guards) - 类型守卫是一种表达式,它执行一些运行时检查,并缩小变量的类型范围
is
关键字通常与类型断言一起使用,以提供更精确的类型信息
基本使用
- 假设我们有一个联合类型,它可以是多种类型之一
- 在某些情况下,我们可能希望缩小这个类型的范围,以进行更具体的操作
- 这就是
is
类型守卫的用途所在
1 ) 示例
type Shape = Circle | Square | Triangle;
interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
sideLength: number;
}
interface Triangle {
kind: "triangle";
base: number;
height: number;
}
function isCircle(shape: Shape): shape is Circle {
return shape.kind === "circle";
}
// 使用 isCircle 函数来缩小 shape 变量的类型范围
function calculateArea(shape: Shape) {
if (isCircle(shape)) {
// 在这里,TypeScript 知道 shape 是 Circle 类型
return Math.PI * shape.radius ** 2;
}
// ... 其他形状的面积计算
// 注意:这里应该包含对所有其他形状的处理,否则如果传入的 shape 不是 Circle 类型,函数将不会返回任何值。
throw new Error("Unsupported shape type");
}
// 定义一个圆的变量
const myCircle: Circle = {
kind: "circle",
radius: 5 // 圆的半径为 5
};
// 调用 calculateArea 方法计算圆的面积
const area = calculateArea(myCircle);
console.log(`The area of the circle is: ${area}`);
- 在上面的代码中,我们定义了一个
isCircle
函数,它接受一个Shape
类型的参数,并返回一个布尔值 - 通过使用
is
关键字,我们告诉 TypeScript,如果这个函数返回 true,那么 shape 参数就一定是Circle
类型 - 在
calculateArea
函数中,当我们调用isCircle(shape)
并检查其返回值时 - TypeScript 知道如果返回 true,则 shape 一定是
Circle
类型 - 因此,我们可以安全地访问 shape.radius 属性,而不用担心类型错误
注意事项
is
关键字只与类型守卫一起使用,用于提供更精确的类型信息- 类型守卫并不改变变量的实际类型,它们只是告诉 TypeScript 编译器在特定条件下变量的类型是什么
- 除了使用
is
关键字外,还可以使用其他方式来实现类型守卫 - 比如使用
typeof
、instanceof
或自定义的守卫函数