Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
An simple instructions on how to use enum in typescript

In TypeScript 1.8+, you can create a string literal type to define the type and an object with the same name for the list of values. It mimics a string enum's expected behaviour.

Here's an example:

type MyStringEnum = "member1" | "member2";

const MyStringEnum = {
    Member1: "member1" as MyStringEnum,
    Member2: "member2" as MyStringEnum

Which will work like a string enum:

// implicit typing example
let myVariable = MyStringEnum.Member1; // ok
myVariable = "member2";                // ok
myVariable = "some other value";       // error, desired

// explict typing example
let myExplicitlyTypedVariable: MyStringEnum;
myExplicitlyTypedVariable = MyStringEnum.Member1; // ok
myExplicitlyTypedVariable = "member2";            // ok
myExplicitlyTypedVariable = "some other value";   // error, desired

Make sure to type all the strings in the object! If you don't then in the first example above the variable would not be implicitly typed to MyStringEnum.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.