0
0
Typescriptprogramming~3 mins

Why Exclude type in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could instantly remove unwanted types without any mistakes or extra work?

The Scenario

Imagine you have a list of different fruit types, but you want to create a new list that excludes one specific fruit, like "banana". Doing this manually means checking each fruit one by one and removing the unwanted ones.

The Problem

This manual way is slow and easy to mess up, especially if the list is long or changes often. You might forget to remove some, or accidentally remove the wrong ones. It's like trying to pick out one color of jellybean from a huge jar by hand.

The Solution

The Exclude type in TypeScript lets you automatically create a new type that leaves out certain unwanted types. It's like having a magic filter that removes the exact things you don't want, without any mistakes or extra work.

Before vs After
Before
type Fruit = 'apple' | 'banana' | 'orange';
type WithoutBanana = 'apple' | 'orange'; // manually written
After
type Fruit = 'apple' | 'banana' | 'orange';
type WithoutBanana = Exclude<Fruit, 'banana'>;
What It Enables

This lets you easily create precise types by removing unwanted parts, making your code safer and easier to maintain.

Real Life Example

For example, if you have a user role system with roles like 'admin', 'editor', and 'viewer', but want to create a type for all roles except 'admin', Exclude does this perfectly without errors.

Key Takeaways

Manually removing types is slow and error-prone.

Exclude type automatically filters out unwanted types.

This makes your TypeScript code cleaner and safer.