TypeScript 类型断言之 is 关键字

如题,is 关键字是 TS 类型断言的一种方式。

我们常用的是另一种,as。as 能满足我们基本的类型断言的需要,如我们单纯的想打印一个变量的某个属性,或者调用它的函数,我们只想执行一次这样的操作,那么 as 就能很好的工作了。

但是有时我们需要对这个变量做一系列的操作,如果每次都需要 as 断言一下,那么就会显得很麻烦,有没有什么办法能实现一次断言,多次操作呢?is 关键字就是来做这个的。

is 关键字用来让用户实现 “类型守卫”,实际上就是一个函数,用来判断类型,类型守卫经常和条件判断一块使用,在判断成功后的代码块中均可认为变量是断言的那个类型,无需每次都 as。

// 自定义类型守卫函数
function isEvenNumber(num: any): num is number {
return typeof num === "number" && num % 2 === 0;
}

// 使用 is 进行类型断言
function doubleIfEven(num: any): any {
if (isEvenNumber(num)) {
// 无论执行多少次操作,都认为 num 是偶数类型
return num * 2;
} else {
return "Not an even number";
}
}

console.log(doubleIfEven(2)); // 输出:4
console.log(doubleIfEven("2")); // 输出:"Not an even number"

类型守卫的参数可以是任意类型,只要能帮你做判断即可:

interface Circle {
kind: 'circle';
radius: number;
}

interface Square {
kind: 'square';
sideLength: number;
}

// 联合类型
type Shape = Circle | Square;

function isCircle(shape: Shape): shape is Circle {
return shape.kind === 'circle';
}

function calculateArea(shape: Shape) {
if (isCircle(shape)) {
// 在这里,shape 被类型细化为 Circle 类型
return Math.PI * shape.radius * shape.radius;
} else {
// 在这里,shape 被类型细化为 Square 类型
return shape.sideLength * shape.sideLength;
}
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注