文章目录
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