Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - How can omit some items from an Enum in TypeScript?

Tags:

typescript

I defined an Enum to clarify APIs request status:

const enum Errcode{     Ok=0,     Error=1,     AccessDeny=201,     PostsNotFound=202,     TagNotFound=203,     //... }  type SuccessErrcode =Errcode.Ok; type NotFoundError =Errcode.PostsNotFound|Errcode.TagNotFound; type ErrorErrcode=/* there */; 

How can I define the ErrorErrcode that means all items of Errcode except Errcode.Ok (and it should include all items of NotFoundError)?

I can't define the more granular types and Union them likes this:

enum SuccessErrcode {     Ok =0, } enum NotFoundErrcode {     PostsNotFound=202,     TagNotFound=203, } enum ErrorErrcode {     Error=1, } type Errcode =SuccessErrcode|NotFoundError|SuccessErrcode; 

If I do this, I will can't use Errcode.xxx - for use a code, I must to know where it be assigned of.(e.g. from Errcode.TagNotFound to NotFoundError.TagNotFound). And consider that - when there have TagErrcode and NotFoundErrcode, the TagNotFound=203 will be defined twice.

like image 577
pea3nut Avatar asked Feb 18 '18 10:02

pea3nut


People also ask

How do you omit an enum?

Use the Exclude utility type to omit values from an enum, e.g. type WithoutMultiple = Exclude<Sizes, Sizes.

Can we change enum values in TypeScript?

An enum is usually selected specifically because it is immutable - i.e. you would never want the values to change as it would make your application unpredictable.

How do I use enum values in TypeScript?

In TypeScript, enums, or enumerated types, are data structures of constant length that hold a set of constant values. Each of these constant values is known as a member of the enum. Enums are useful when setting properties or values that can only be a certain number of possible values.


2 Answers

As of TypeScript 2.8 and the addition of conditional types, you can use the built-in Exclude to exclude certain enum values:

const enum Errcode {     Ok=0,     Error=1,     AccessDeny=201,     PostsNotFound=202,     TagNotFound=203,     //... }  type SuccessErrcode = Errcode.Ok; type NotFoundError = Errcode.PostsNotFound|Errcode.TagNotFound; type ErrorErrcode = Exclude<Errcode, Errcode.Ok>; 

Typescript Playground

like image 110
user1234 Avatar answered Oct 04 '22 19:10

user1234


You would first define the more granular types. Perhaps something like this:

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

You can then define a Union Type to be either a SuccessCode or a ErrorCode:

type ResultCode = ErrorCode | SuccessCode; 

which you can then use like this:

const myResult1: ResultCode = ErrorCode.AccessDeny; const myResult2: ResultCode = SuccessCode.Ok; 
like image 25
Stewart_R Avatar answered Oct 04 '22 21:10

Stewart_R