Photo by Stijn Swinnen on Unsplash

Have you ever thought how you can get a type out of a composite type?

type Puppy = Animal<BigEyes, SmallNose, SmallEars>;

...

type PuppyEyes = ExtractEyes<Puppy>;

What is this ExtractEyes ? How does it work?

Some background first.

Conditional Types

TypeScript 2.8 has introduced a new feature called conditional types.

This allows you to have more control of types that are quite fluid/dynamic.

T extends U ? X : Y

I don’t want to try and explain what this is and how this can be applied, there are many resources out there which explain this idea better than the official documentation.

The best piece about conditional types I found is here by David Sheldrick.

I encourage you to read this before continuing as it will organise this concept for you and will help you understand what we achieved.

Let’s Make Pizzas!

Well, the example we’ll work with won’t be about puppies, but rather pizzas.

Guess I was hungry while writing this..

Let’s define a pizza that we can add toppings to it.

We have a generic pizza class, a couple of topping options and a preset of a pizza Margherita.

Next, we’ll create a function that receives a toppings type, and will expose us functions to help us purchase the toppings so we could make the pizza.

So, now if we try and purchase pizza margherita, we will have type completion!