首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何筛选父类型,以便在TypeScript中选择给定类型的子类型?

在TypeScript中,可以使用类型谓词(Type Predicate)来筛选父类型,以便选择给定类型的子类型。类型谓词是一种用于在运行时检查类型的方法。

要筛选父类型,可以使用instanceof关键字结合自定义类型谓词函数。类型谓词函数是一个返回布尔值的函数,它的参数是一个待检查的变量,并且在函数体内部使用instanceof关键字来判断变量的类型。

下面是一个示例:

代码语言:txt
复制
class Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}

class Dog extends Animal {
  breed: string;
  constructor(name: string, breed: string) {
    super(name);
    this.breed = breed;
  }
}

class Cat extends Animal {
  color: string;
  constructor(name: string, color: string) {
    super(name);
    this.color = color;
  }
}

function isDog(animal: Animal): animal is Dog {
  return animal instanceof Dog;
}

function isCat(animal: Animal): animal is Cat {
  return animal instanceof Cat;
}

const animals: Animal[] = [
  new Dog("Buddy", "Labrador"),
  new Cat("Kitty", "White"),
  new Dog("Max", "Golden Retriever")
];

const dogs: Dog[] = animals.filter(isDog);
const cats: Cat[] = animals.filter(isCat);

console.log(dogs); // 输出:[Dog { name: 'Buddy', breed: 'Labrador' }, Dog { name: 'Max', breed: 'Golden Retriever' }]
console.log(cats); // 输出:[Cat { name: 'Kitty', color: 'White' }]

在上面的示例中,我们定义了Animal作为父类型,DogCat作为子类型。然后,我们使用isDogisCat两个类型谓词函数来筛选出animals数组中的狗和猫。最后,我们将筛选结果分别赋值给dogscats数组,并打印输出。

这样,我们就可以根据自定义的类型谓词函数来筛选出给定类型的子类型。在实际应用中,可以根据具体需求和业务逻辑来定义和使用类型谓词函数。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券