Skip to content

Enums ​

A basic enum ​

Members count up from 0:

ts
enum State {
    Idle,
    Walking,
    Jumping,
}

const s: State = State.Walking;
console.log(s);    // 1

The type of a member is the enum, so declare the variable as State, not int.

Explicit values ​

ts
enum Direction {
    Up = "UP",
    Down = "DOWN",
}

enum Status {
    Unknown,
    Active = 10,
    Pending,
}

console.log(Direction.Up, Status.Pending);    // UP 11

After an explicit number, counting carries on from it.

Bitflags ​

enum bitflag gives each member its own bit (1, 2, 4, 8 and so on), so you can combine them:

ts
enum bitflag Permission {
    Read,
    Write,
    Execute,
}

const p: int = Permission.Read | Permission.Write;
console.log(p);    // 3

switch bitflag tests each case with a bitwise AND, so more than one case can run:

ts
enum bitflag Perm {
    Read,
    Write,
    Execute,
}

const granted: int = Perm.Read | Perm.Write;

switch bitflag (granted) {
    case Perm.Read:
        console.log("can read");
        break;
    case Perm.Write:
        console.log("can write");
        break;
    case Perm.Execute:
        console.log("can execute");
        break;
}

In a switch bitflag, break moves on to the next case. stop leaves the whole switch.

Exhaustive switches ​

switch strict makes the checker confirm that every member of the enum has a case. Add a member later and every switch strict that misses it becomes an error:

ts
enum Suit {
    Hearts,
    Spades,
}

function suitName(suit: Suit): string {
    switch strict (suit) {
        case Suit.Hearts:
            return "hearts";
        case Suit.Spades:
            return "spades";
    }
    return "";
}

console.log(suitName(Suit.Spades));

Doc comments ​

/** */ comments on members show up in IDE hover and autocomplete:

ts
enum HttpStatus {
    /** The request succeeded. */
    Ok = 200,
    /** Nothing at that path. */
    NotFound = 404,
}

console.log(HttpStatus.NotFound);