• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

String Enums In TypeScript

TypeScript · May 30, 2016

Sometimes you want to specify in your application multiple allowed values. For example, you might have a method which allows you to perform server requests and the only allowed values are; GET, POST, UPDATE, DELETE and PUT.

Ideally you want to prevent any developer from calling a method with an invalid value. Normally you would use an enum for this, most languages support the use of an enum which might be used for this purpose.

Unfortunately, in TypeScript, enums only support numeric values, not strings. Although, there is an issue here which is calling for it to be extended to strings and other types, like other languages such as C++ allow.

In an ideal world it would be nice to be able to do this in TypeScript:

enum stateEnums {
    "on",
    "off"
}

export class MyClass {
    private componentState: stateEnums;

    on() {
        this.componentState = "on";
    }

    off() {
        this.componentState = "off";
    }
}

Except, because we can’t use an enum in this way, we can use a type instead, the end result isn’t too different:

type stateEnums = "on" | "off";

export class MyClass {
    private componentState: stateEnums;

    on() {
        this.componentState = "on";
    }

    off() {
        this.componentState = "off";
    }
}

Not only that, but you can also add in a boolean and possibly other values into the mix as well. You are essentially creating a map of values that will be checked when the value utilising the type is changed. Akin to a “only allow these values and none other”

type stateEnums = "on" | "off" | boolean;

export class MyClass {
    private componentState: stateEnums;

    on() {
        this.componentState = "on";
    }

    off() {
        this.componentState = "off";
    }

    onTrue() {
        this.componentState = true;
    }

    offFalse() {
        this.componentState = false;
    }
}

Conclusion

You probably already knew the above, but if not, hopefully this helped you. I am quite knew to the TypeScript side myself, so if there is an even better way of achieving the above (perhaps changing how enums work), then feel free to leave a comment and enlighten us.

Dwayne

Leave a ReplyCancel reply

0 Comments
Inline Feedbacks
View all comments

Primary Sidebar

Popular

  • Handling Errors with the Fetch API
  • How To Get The Hash of A File In Node.js
  • Testing Event Listeners In Jest (Without Using A Library)
  • The Quad Cortex Desktop Editor is Finally Announced
  • Thoughts on the Flipper Zero

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz