Implement the `LookUp<U, T>` type, that looks up a type in a union by its attributes. Learn union type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement the LookUp<U, T> type, that looks up a type in a union by its attributes. This is especially useful when you are working with discriminated unions.
Sometimes, you may want to look up a type in a union by its attributes.
In this challenge, we would like to get the corresponding type by searching for the common type field in the union Cat | Dog. In other words, we will expect to get Dog for LookUp<Dog | Cat, 'dog'> and Cat for LookUp<Dog | Cat, 'cat'> in the following example.
interface Cat {
type: 'cat'
breeds: 'Abyssinian' | 'Shorthair' | 'Curl' | 'Bengal'
}
interface Dog {
type: 'dog'
breeds: 'Hound' | 'Brittany' | 'Bulldog' | 'Boxer'
color: 'brown' | 'white' | 'black'
}
type MyDogType = LookUp<Cat | Dog, 'dog'> // expected to be `Dog`Change the following code to make the test cases pass (no type check errors).
type LookUp<U, T> = U extends { type: T } ? U : neverHow it works:
U extends { type: T }.U, otherwise we return never.This challenge helps you understand union type manipulation and how to apply this concept in real-world scenarios.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount