关键词: TypeScript, TypeChallenge
有时,您可能希望根据其属性在并集中查找类型。
在此挑战中,我们想通过在联合类型Cat | Dog
中搜索公共type
字段来获取相应的类型。
换句话说,在以下示例中,我们期望LookUp<Dog | Cat, 'dog'>
获得Dog
,LookUp<Dog | Cat, 'cat'>
获得Cat
。
interface Cat {
type: "cat";
breeds: "Abyssinian" | "Shorthair" | "Curl" | "Bengal";
}
interface Dog {
type: "dog";
breeds: "Hound" | "Brittany" | "Bulldog" | "Boxer";
color: "brown" | "white" | "black";
}
type MyDog = LookUp<Cat | Dog, "dog">; // expected to be `Dog`
type LookUp<
T extends { type: string },
N extends T extends { type: infer K } ? K : never
> = T extends { type: N } ? T : never;
首先约束待查找的类都有type
字段: T extends { type: string }
其次约束查找的名字在几种类型的 type 名字之中: N extends T extends { type: infer K } ? K : never
对于返回类型, 使用extends
对T
做"分配"
的操作, 对于T
这个联合类型中的每一项, 检查其type
字段是否和传入参数相同, 是就返回此项, 否则检查下一个
最终代码如下
type LookUp<
T extends { type: string },
N extends T extends { type: infer K } ? K : never
> = T extends { type: N } ? T : never;