Yuzhe's Blog

yuzhes

查找类型

查找类型

题目链接

题目

有时,您可能希望根据某个属性在联合类型中查找类型。

在此挑战中,我们想通过在联合类型Cat | Dog中通过指定公共属性type的值来获取相应的类型。换句话说,在以下示例中,LookUp<Dog | Cat, 'dog'>的结果应该是DogLookUp<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<U, T> = U extends { type: T } ? U : never

这里利用了条件类型的特性,如果extends左侧的类型是一个联合类型,那么这个类型会被分发,即会遍历联合类型的每一个成员。然后将结果合并为一个联合类型。

那么只有当U中的type属性的值等于T时,才会返回U,否则返回never

这里举一个例子。


type A = { type: 'a' }
type B = { type: 'b' }

type C = A | B

// Note that the following is not a valid TypeScript code, just for illustration
type t 
  = LookUp<C, 'a'>
  // the calculation process is as follows
  = C extends { type: 'a' } ? C : never
  = A | B extends { type: 'a' } ? A | B : never
  = A extends { type: 'a' } ? A : never | B extends { type: 'a' } ? B : never
  = A | never
  = A