0
0
Typescriptprogramming~30 mins

Distributive conditional types in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Distributive Conditional Types in TypeScript
📖 Scenario: Imagine you have a list of different fruits and vegetables. You want to create a type that tells you if each item is a fruit or not. This helps you organize your shopping list better.
🎯 Goal: You will build a TypeScript type called IsFruit that checks if a given item is a fruit using distributive conditional types. Then, you will apply it to a union of items and see the results.
📋 What You'll Learn
Create a union type called Items with the values 'apple', 'carrot', and 'banana'.
Create a type called IsFruit that uses a distributive conditional type to check if a type extends 'apple' | 'banana'.
Create a new type called Result that applies IsFruit to Items.
Print the Result type to see which items are fruits.
💡 Why This Matters
🌍 Real World
Distributive conditional types help you create flexible and reusable type checks in TypeScript, which is useful when working with complex data structures.
💼 Career
Understanding distributive conditional types is important for TypeScript developers to write safer and more expressive code, especially in large projects or libraries.
Progress0 / 4 steps
1
Create the union type Items
Create a union type called Items with the exact values 'apple', 'carrot', and 'banana'.
Typescript
Need a hint?

Use the | symbol to combine string literal types into a union.

2
Create the distributive conditional type IsFruit
Create a type called IsFruit that takes a generic type T and returns 'Yes' if T extends 'apple' | 'banana', otherwise returns 'No'. Use a conditional type with T extends 'apple' | 'banana' ? 'Yes' : 'No'.
Typescript
Need a hint?

Use extends in a conditional type to check if T is one of the fruits.

3
Apply IsFruit to Items to create Result
Create a new type called Result that applies IsFruit to the union type Items.
Typescript
Need a hint?

Apply the conditional type to the union to get a new union of results.

4
Print the Result type
Write a line to print the string 'Yes' | 'No' which represents the Result type. Use console.log with a string showing the expected union type.
Typescript
Need a hint?

TypeScript types do not exist at runtime, so print the expected union as a string.