#62•Medium

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

ChallengeSolution
// Video Solution: https://youtube.com/watch?v=cgXsg7KeVAE

/* _____________ Your Code Here _____________ */

type LookUp<U, T> = any

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '../helpers'

interface Cat {
  type: 'cat'
  breeds: 'Abyssinian' | 'Shorthair' | 'Curl' | 'Bengal'
}

interface Dog {
  type: 'dog'
  breeds: 'Hound' | 'Brittany' | 'Bulldog' | 'Boxer'
  color: 'brown' | 'white' | 'black'
}

type Animal = Cat | Dog

type cases = [
  Expect<Equal<LookUp<Animal, 'dog'>, Dog>>,
  Expect<Equal<LookUp<Animal, 'cat'>, Cat>>,
]

Pro Challenge

Get access to all 200+ challenges, including every medium, hard, and extreme one.

One-time payment, lifetime access. 30-day money-back guarantee.

Video Walkthrough

Detailed Explanation

[object Object]

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

Related Challenges

Learn the Concepts

Become a TypeScript Pro

Track your progress through 200+ hands-on challenges. Free, sign in with GitHub.

Or start solving right away: explore all TypeScript challenges