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

Solution 1:

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:

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;