0
0
Typescriptprogramming~5 mins

Exclude type in Typescript

Choose your learning style9 modes available
Introduction

The Exclude type helps you remove specific types from a group of types. It makes your code clearer and safer by excluding unwanted types.

When you want to create a new type without certain values from an existing type.
When you want to prevent some values from being used in a function or variable.
When you want to narrow down a type by removing options that don't apply.
When you want to handle only specific cases in your code by excluding others.
Syntax
Typescript
Exclude<UnionType, ExcludedMembers>

UnionType is the original set of types.

ExcludedMembers are the types you want to remove from UnionType.

Examples
This removes 'green' and 'blue' from Colors, so PrimaryColors is just 'red'.
Typescript
type Colors = 'red' | 'green' | 'blue';
type PrimaryColors = Exclude<Colors, 'green' | 'blue'>;
This excludes 2 and 3 from the numbers, leaving 1 and 4.
Typescript
type Numbers = 1 | 2 | 3 | 4;
type WithoutTwoAndThree = Exclude<Numbers, 2 | 3>;
This removes boolean from the union, keeping only string and number.
Typescript
type Mixed = string | number | boolean;
type OnlyStringAndNumber = Exclude<Mixed, boolean>;
Sample Program

This program defines a type Pets with four animals. Then it creates NoFish by excluding 'fish'. The function adoptPet only accepts pets except 'fish'. Trying to adopt 'fish' causes an error.

Typescript
type Pets = 'dog' | 'cat' | 'fish' | 'bird';
type NoFish = Exclude<Pets, 'fish'>;

function adoptPet(pet: NoFish) {
  console.log(`You adopted a ${pet}.`);
}

adoptPet('dog');
// adoptPet('fish'); // This line will cause a TypeScript error
OutputSuccess
Important Notes

Exclude works only with union types.

It helps catch mistakes early by preventing unwanted types.

Summary

Exclude removes specific types from a union.

It makes your types more precise and your code safer.

Use it when you want to block certain values from a type.