假设我有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];
但它并没有按预期工作。我差点就要回答这个问题了吗?