假设我有 3 种类型和它们的联合类型:
type Cat = {
owner: string;
color: string;
lives: number;
}
type Dog = {
owner: string;
color: string;
}
type Wolf = {
color: string;
}
type Animals = Cat | Dog | Wolf;
我想要一个过滤器AnimalsFilter<U, K>
会像这样工作:
type FilterAnimals<U, K extends string> = ...;
type WithOwner = FilterAnimals<Animals, 'owner'>;
// WithOwner = Cat | Dog
这样过滤这个联合类型后就只有 Cat 和 Dog 了。我怎样才能实现这一目标?
我尝试了映射,如下所示:
type FilterAnimals<U, K extends string> = {
[Key in keyof U]: Key extends K? U[K] : never;
}[keyof U];
但它没有按预期工作。我是否已经接近回答这个问题了?
最佳答案
您可以写HasKey<T, K>
作为distributive conditional type拆分 union type T
进入其成员,然后通过 keyof
执行另一个条件检查让这些成员拥有 K
的 key 。像这样:
type HasKey<T, K extends PropertyKey> =
T extends unknown ? K extends keyof T ? T : never : never;
type AnimalsWithOwner = HasKey<Animals, "owner">;
// type AnimalsWithOwner = Cat | Dog
关于typescript - 如何在 TypeScript 中过滤类似对象的联合类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77729861/