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

Typescript

Typescript 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>;

Typescript Playground

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionpea3nutView Question on Stackoverflow
Solution 1 - Typescriptuser1234View Answer on Stackoverflow
Solution 2 - TypescriptStewart_RView Answer on Stackoverflow