Skip to content

Instantly share code, notes, and snippets.

@kccheung
Created March 12, 2017 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kccheung/ce165a6eefc5e41d2f669a7ec50d0052 to your computer and use it in GitHub Desktop.
Save kccheung/ce165a6eefc5e41d2f669a7ec50d0052 to your computer and use it in GitHub Desktop.
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