- typeof 类型保护:
typeof
操作符可以用于在运行时检查变量的类型,从而在条件分支中缩小类型范围。
- 示例代码:
function printValue(value: string | number) {
if (typeof value ==='string') {
console.log(value.length);
} else {
console.log(value.toFixed(2));
}
}
printValue('hello');
printValue(123);
- instanceof 类型保护:
instanceof
用于检查一个对象是否是某个类的实例,在面向对象编程中可缩小类型范围。
- 示例代码:
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
function handleAnimal(animal: Animal) {
if (animal instanceof Dog) {
console.log('This is a dog');
} else if (animal instanceof Cat) {
console.log('This is a cat');
}
}
const dog = new Dog();
const cat = new Cat();
handleAnimal(dog);
handleAnimal(cat);
- in 类型保护:
in
操作符用于检查对象中是否包含某个属性,以此来缩小类型范围。
- 示例代码:
interface HasName {
name: string;
}
interface HasAge {
age: number;
}
function printInfo(person: HasName | HasAge) {
if ('name' in person) {
console.log(`Name: ${person.name}`);
} else if ('age' in person) {
console.log(`Age: ${person.age}`);
}
}
const person1: HasName = { name: 'Alice' };
const person2: HasAge = { age: 30 };
printInfo(person1);
printInfo(person2);
- 自定义类型保护函数:
- 可以通过自定义函数来实现类型保护,函数返回一个类型谓词。
- 示例代码:
function isString(value: any): value is string {
return typeof value ==='string';
}
function processValue(value: string | number) {
if (isString(value)) {
console.log(value.toUpperCase());
} else {
console.log(value * 2);
}
}
processValue('world');
processValue(42);