#62Medium

Type Lookup

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.

Challenge Instructions: Type Lookup

Medium

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).

Loading...

Video Walkthrough

Detailed Explanation

type LookUp<U, T> = U extends { type: T } ? U : never

How it works:

This challenge helps you understand union type manipulation and how to apply this concept in real-world scenarios.

This challenge is originally from here.

Share this challenge

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount