Categories
TypeScript Answers

How to omit some items from an enum in TypeScript?

Spread the love

Sometimes, we want to omit some items from an enum in TypeScript.

In this article, we’ll look at how to omit some items from an enum in TypeScript.

How to omit some items from an enum in TypeScript?

To omit some items from an enum in TypeScript, we can use the Exclude type.

For instance, we write

enum ErrCode {
  Ok = 0,
  Error = 1,
  AccessDeny = 201,
  PostsNotFound = 202,
  TagNotFound = 203,
}

type ErrorErrcode = Exclude<ErrCode, ErrCode.Ok>;

to use Exclude to exclude the ErrCode.Ok value from the ErrCode type and return that as the type.

Then we assign that to the ErrorErrcode type alias.

Conclusion

To omit some items from an enum in TypeScript, we can use the Exclude type.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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