TS类型守卫

举报
林太白 发表于 2025/03/27 10:09:27 2025/03/27
【摘要】 TS类型守卫

❤ TS类型守卫

🌟认识类型守卫(Type Guards)

类型守卫(Type Guards)运行时检查变量的类型,推断变量的类型,根据结果做出不同的处理或推断,确保类型安全,避免运行时错误。

具体描述就是:

类型保护是可执行运行时检查的一种表达式,确保该类型在一定的范围内。

就是确保是规定的类型

类型保护与特性检测并不是完全不同,主要思想是尝试检测属性、方法或原型,以确定如何处理值

👉类型守卫的几种方式

类型守卫方式 示例代码 说明
typeof 类型守卫 if (typeof value === "string"){ ... } 用于检查基本类型(如 stringnumberboolean 等)
instanceof 类型守卫 if (value instanceof Date) { ... } 用于检查对象实例是否属于某个类或构造函数的实例。
自定义类型守卫函数 function isString(value: any): value is string { return typeof value === "string"; } 定义一个返回类型谓词的函数
用于对某些类型进行更复杂的检查。
in 操作符 if ("name" in value) { ... } 用于检查对象是否包含指定的属性。
Array.isArray if (Array.isArray(value)) { ... } 用于判断一个值是否是数组。
null/undefined 检查 if (value !== null && value !== undefined) { ... } 通过显式检查是否为 nullundefined 来细化类型。
Object.prototype.hasOwnProperty if (value.hasOwnProperty("property")) { ... } 检查对象是否具有某个属性,用于复杂对象

🌟typeof类型守卫

typeof检查基本数据类型(如 string, number, boolean)

function isFuntype(value:string|number){
	if(typeof value ==='string'){
		return value.length;
	}else{
		return value.toString().length;
	}
}
console.log(isFuntype('1234')); //输出 4
console.log(isFuntype(2222)); //输出 4

🌟instanceof类型守卫

class Dog {
    bark() {
        console.log("Woof!");
    }
}

class Cat {
    meow() {
        console.log("Meow!");
    }
}

function makeSound(animal:Dog | Cat){
	if (animal instanceof Dog) {
        // animal 在此被推断为 Dog 类型
        animal.bark();
    } else {
        // animal 在此被推断为 Cat 类型
        animal.meow();
    }
}
console.log('dog');
const dog = new Dog();
makeSound(dog); // 输出: Woof!


console.log('cats');
const cats = new Cat();
makeSound(cats); // 输出: Woof!

🌟自定义类型守卫(通过返回类型为 is 的函数)

核心:通过animal is Dog 返回true或者false定义返回,再使用 判断animal是否包含 bark 属性

interface Dog {
  bark(): void;
}

interface Cat {
 meow(): void;
}


function isDog(animal: Dog | Cat ) : animal is Dog{
	return (animal as Dog).bark!==undefined;
}
function makeanimal(animal:Cat | Dog){
	if(isDog(animal)){
		return animal.bark();
	}else{
		return animal.meow();
	}
}
const dog: Dog = { bark: () => console.log("Woof!") };
makeanimal(dog);

注解

animal is Cat(类型谓词)帮助我们进行类型缩小

告诉编译器某个变量的类型范围,确保代码安全和类型准确

把上面的例子完善一下

interface Dog {
	bark(): void;
}
interface Cat {
	meow(): void;
}

function isDog(animal: Cat | Dog): animal is Dog {
	return (animal as Dog).bark !== undefined;
}
function isCat(animal: Cat | Dog): animal is Cat {
	return (animal as Cat).meow !== undefined;
}
const dag: Dog = {
	bark: () => {
		console.log("Dog!");
	}
}

const cat: Cat = {
	meow: () => {
		console.log("Cat!");
	}
}
console.log(isDog(dag), 'dag');
console.log(isDog(cat), '非dag');

console.log(isCat(cat), 'Cat');
console.log(isCat(dag), '非Cat');

//输出
// true dag
// false 非dag
// true Cat
// false 非Cat

🌟in操作符类型守卫

核心:通过in判断animal 是否包含 bark 属性

interface Dog {
  bark(): void;
}
interface Cat {
 meow(): void;
}
function makeAnimal(animal:Cat | Dog){
	if("bark" in animal){
		animal.bark();
	}else{
		animal.meow();
	}
}
const dog:Dog={bark:()=>{
	console.log("Woof!");
}}
makeAnimal(dog); // 输出: Woof!
【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。