简体   繁体   中英

String enums in typescript

I would like to have a set of string enums in typescript so I can do things like having the user select from a set of predefined options.

I found a good solution in this answer: How to convert string to enum in TypeScript?

However, that only works for single words... (basically, the above allows you to get the enum name value -- and that can't have a space in it).

So, further looking, I found this person with a workaround: Workaround for string based enums in typescript

That will allow something like this to work:

export enum EventType {
    Photoshoot = <any>"Photoshoot",
    BookingMeeting = <any>"Booking Meeting",
    PostShootMeeting = <any>"Post Shoot Meeting",
    Purchase = <any>"Purchase",
    Print = <any>"Print"
}

The only response basically says doing so is unsafe. (but I should say, it DOES work -- I can type EventType. dot ... and Atom editor gives me the 5 camel-case options to select from (keeping things consistent in the code) I can then use that to have the string value spit out to give my users a good space-filled experience, in the future I can change the enum and for different languages/option wording without messing with the 'code' at all, etc...

Is there a better way to do this? I'd rather not do it 'unsafely' -- but I don't know of any other way.

TypeScript enums are number based. You can use string literals with union types to mock a string based enum as in the CardinalDirection example below.

type CardinalDirection =
    "North"
    | "East"
    | "South"
    | "West";

function move(distance: number, direction: CardinalDirection) {
    // ...
}

move(1,"North"); // Okay
move(1,"Nurth"); // Error!

here's more: https://basarat.gitbooks.io/typescript/content/docs/types/literal-types.html

the string enums are in the offing https://github.com/Microsoft/TypeScript/issues/3192

Update for TS 2.4 - 2017+

String Enums are available starting in TypeScript 2.4 using the following syntax:

enum Color {
    Red = "red",
    Green = "green",
    Blue = "blue"
}

Demo in TS Playground

Further Reading

You have other options, as described in Reverse-Mapping for String Enums .

Here is an example:

type EventType = "Photoshoot" | "Booking Meeting" | "Post Shoot Meeting" | "Purchase" | "Print";
const EventType {
    get Photoshoot(): EventType { return "Photoshoot"; },
    get BookingMeeting(): EventType { return "Booking Meeting"; },
    get PostShootMeeting(): EventType { return "Post Shoot Meeting"; },
    get Purchase(): EventType { return "Purchase"; },
    get Print(): EventType { return "Print"; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM