在 TypeScript 中,区分不同的对象类型可以通过多种方式实现,具体取决于你的需求和对象的结构。以下是几种常见的方法:
in
操作符: in
操作符可以检查对象是否具有特定的属性,从而区分不同的对象类型。instanceof
操作符: instanceof
操作符可以检查对象是否是某个类的实例。以下是每种方法的示例:
interface Dog {
type: 'dog';
bark: () => void;
}
interface Cat {
type: 'cat';
meow: () => void;
}
type Animal = Dog | Cat;
function handleAnimal(animal: Animal) {
if (animal.type === 'dog') {
animal.bark();
} else if (animal.type === 'cat') {
animal.meow();
}
}
const myDog: Dog = { type: 'dog', bark: () => console.log('Woof!') };
const myCat: Cat = { type: 'cat', meow: () => console.log('Meow!') };
handleAnimal(myDog); // Output: Woof!
handleAnimal(myCat); // Output: Meow!
type Dog = {
bark: () => void;
};
type Cat = {
meow: () => void;
};
type Animal = Dog | Cat;
function isDog(animal: Animal): animal is Dog {
return (animal as Dog).bark !== undefined;
}
function handleAnimal(animal: Animal) {
if (isDog(animal)) {
animal.bark();
} else {
(animal as Cat).meow();
}
}
const myDog: Dog = { bark: () => console.log('Woof!') };
const myCat: Cat = { meow: () => console.log('Meow!') };
handleAnimal(myDog); // Output: Woof!
handleAnimal(myCat); // Output: Meow!
in
操作符type Dog = {
bark: () => void;
};
type Cat = {
meow: () => void;
};
type Animal = Dog | Cat;
function handleAnimal(animal: Animal) {
if ('bark' in animal) {
animal.bark();
} else {
animal.meow();
}
}
const myDog: Dog = { bark: () => console.log('Woof!') };
const myCat: Cat = { meow: () => console.log('Meow!') };
handleAnimal(myDog); // Output: Woof!
handleAnimal(myCat); // Output: Meow!
instanceof
操作符class Dog {
bark() {
console.log('Woof!');
}
}
class Cat {
meow() {
console.log('Meow!');
}
}
type Animal = Dog | Cat;
function handleAnimal(animal: Animal) {
if (animal instanceof Dog) {
animal.bark();
} else if (animal instanceof Cat) {
animal.meow();
}
}
const myDog = new Dog();
const myCat = new Cat();
handleAnimal(myDog); // Output: Woof!
handleAnimal(myCat); // Output: Meow!
领取专属 10元无门槛券
手把手带您无忧上云