【TS】TypeScript 类型守卫、类型保护、类型缩小

文章目录

typeof类型守卫

instanceof类型守卫

in类型守卫

等值类型守卫

自定义函数类型守卫


TypeScript 类型缩小就是从宽类型转化为窄类型的过程,常用于处理联合类型变量的场景。

类型保护通常用于缩小类型,类型保护的主要思想是尝试检测属性、方法或原型,以确定如何处理值。

类型保护会在运行时检查变量以确保 TS 变量在特定的块级作用域内属于特定的类型,通常使用在条件块语句中。检测变量的正确方法、原型和属性,提示并规避不合法的操作,提高代码质量。

类型守卫的作用在于,在语句的块级作用域【if语句内或三目运算符表达式内】触发类型缩小。类型守卫返回一个布尔值,接受一个类型并告诉TypeScript是否可以缩小到更具体的类型。

类型守卫包括 typeof、instanceof、in、 ==、===、!=、!== 和自定义类型守卫等。

typeof类型守卫

typeof 操作符:检查一个变量是否为某一类型

string、number、boolean、symbol、undefined、object、function、bigint

function getType(params: string | number) {
    if (typeof params === 'string') {
        return params.length // 正确
    } else {
        return params.length // 报错
    }
}
console.log(getType("abc")); // 3
console.log(getType(12345)); // undefined

instanceof类型守卫

instanceof 操作符:检查一个值是否是一个类的实例

// 定义类
class Dog {
    wang = 'wangwang'
}
class Cat {
    miao = 'miaomiao'
}
// 定义函数
const getName = (animal: Dog | Cat) => {
    if (animal instanceof Dog) {
        return animal.wang
    } else if (animal instanceof Cat) {
        return animal.miao
    }
}
// 实例化创建类
const cat = new Cat();
const dog = new Dog();
// 调用函数
console.log(getName(cat)); // miaomiao
console.log(getName(dog)); // wangwang

in类型守卫

in 操作符:用来确定对象是否具有某个属性

// 定义对象类型
type Fish = {
    swim: () => void
}
type Bird = {
    fly: () => void
}
// 实现对象
let bird: Bird = {
    fly(): void { console.log('bird'); }
}
let fish: Fish = {
    swim(): void { console.log('fish'); }
}

function move(animal: Fish | Bird) {
    if ("swim" in animal) {
        animal.swim();
    } else {
        animal.fly();
    }

}
move(fish); // fish
move(bird); // bird

等值类型守卫

全等(===)、全不等(!==)、等于(==)、不等于(!=)操作符:用于检查字面量类型或具体值

type Foo = {
    kind: 'foo'; // 字面量类型
    foo: number;
};
type Bar = {
    kind: 'bar'; // 字面量类型
    bar: number;
};

function doStuff(arg: Foo | Bar) {
    if (arg.kind === 'foo') {
        console.log(arg.foo); // 正确
        console.log(arg.bar); // 报错
    } else {
        console.log(arg.foo); // 报错
        console.log(arg.bar); // 正确
    }
}

自定义函数类型守卫

在开发的时候往往会把一些类型判断封装成函数,这个函数的返回值类型必须是类型谓词(格式:参数名 is 类型

下面示例中,pet is Fish 就是所谓的类型谓词,意思是:如果 pet 里面有 swim 这个属性,pet 就是 Fish 类型。

function isFish(pet: Fish | Bird): pet is Fish {
    return (<Fish>pet).swim !== undefined;
}
// 定义接口
interface Bird {
    fly(): void;
}
interface Fish {
    swim(): void;
}
// 实现接口
let bird: Bird = {
    fly(): void { console.log('bird'); }
}
let fish: Fish = {
    swim(): void { console.log('fish'); }
}
// 自定义函数类型守卫
function isFish(pet: Fish | Bird): pet is Fish {
    return (<Fish>pet).swim !== undefined;
}

function getPet(pet: Fish | Bird): void {
    if (isFish(pet)) {
        pet.swim();
    }
    else {
        pet.fly();
    }
}
getPet(fish); // fish
getPet(bird); // bird

TypeScript 教程——阮一峰·著

TypeScript 中文网

TypeScript 官网

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值