Skip to content

❤ 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.isArrayif (Array.isArray(value)) { ... }用于判断一个值是否是数组。
null/undefined 检查if (value !== null && value !== undefined) { ... }通过显式检查是否为 nullundefined 来细化类型。
Object.prototype.hasOwnPropertyif (value.hasOwnProperty("property")) { ... }检查对象是否具有某个属性,用于复杂对象

🌟typeof

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

JS
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

JS
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 属性

JS
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);

注解

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

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

把上面的例子完善一下

JS
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 属性

JS
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!

Released under the MIT License.