How To Omit Values From an Enum in TypeScript

During the coding process, there are many times when we want to omit values from an Enum in TypeScript. For example, when you want to manipulate the data returned from the online api server. This article will show you how to do it using the Exclude utility type. Let’s get started.

Omit values from an Enum in TypeScript

Exclude utility type

Let’s say you have a situation where you want to use Enum but don’t want some value in the list of valid values. This can actually happen in API responses. For example, let’s say you have a standard API response type, and under certain circumstances, you want to remove a field from that API type.

Exclude utility type can be used here. Pass in a regular match type and specify the member to remove from that argument in the second argument.

Syntax:

Exclude<Type, ExcludedMembers>

Parameter:

Type: is data you want to omit values.
ExcludedMembers: is the item you don’t want to appear in the new data type

Return Value:
Returns a new data type after removing items.

Example:

type fruits = "apple" | "banana" | "cherry";

// Use Exclude utility type to remove apple from fruits
let noApple: Exclude<fruits, "apple">;

Use Exclude utility type with Enum

Enum is a new type of data supported by TypeScript. Most object-oriented languages (such as Java and C#) use it, which is now available in TypeScript. Enum lets you declare a set of named constants. This is a set of related values that can be numbers or strings.

As TypeScript version 2.8, you can use the Exclude utility type to omit values from an Enum. Exclude connection types allows you to exclude specific members of a specified link type. This means that you can take an existing type and remove elements of that type under certain circumstances.

Example:

enum Season {
	Winter,
	Spring,
	Summer,
	Fall,
}

// Use Exclude utility type to remove winter from season
type seasonWithoutWinter = Exclude<Season, Season.Winter>;

// Use Exclude utility type to remove winter and spring from season
type seasonWithoutMultiple = Exclude<Season, Season.Winter | Season.Spring>;

You can also exclude the value directly instead of the element.

Example:

enum Season {
	Winter = 0,
	Spring = 1,
	Summer = 2,
	Fall = 3,
}

// Use Exclude utility type exclude the value of Winter directly
type seasonWithoutWinter = Exclude<Season, 0>;

// Use Exclude utility type exclude the value of Winter and Spring
type seasonWithoutMultiple = Exclude<Season, 0 | 1>;

Summary

So through this article, we have understood how to omit values from an Enum in TypeScript using the Exclude utility type. Hope the article is helpful to you. Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *