TypeScript - How can omit some items from an Enum in TypeScript?
TypescriptTypescript Problem Overview
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.
Typescript Solutions
Solution 1 - Typescript
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>;
Solution 2 - Typescript
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;