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.
Use the Exclude utility type to omit values from an enum, e.g. type WithoutMultiple = Exclude<Sizes, Sizes.
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.
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.
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With