zeroin zeroin -4 years ago 112
TypeScript Question

Workaround for string based enums in typescript

So I found a suggestion that in typescript you can have string-based enums using this syntax:

export enum TextAlign {
Left = <any>"start",
Right = <any>"end",
Center = <any>"middle"

Are there any drawbacks of using this approach?

There is a suggestion to use String Literal Type instead, although I find the enum more comfortable, as you can iterate through values.

Answer Source

Are there any drawbacks of using this approach?

Safety e.g.

let x:number = TextAlign.Left; // compiles fine but actually you just assigned a string to number


Every time you assert you are potentially lying to the compiler : and these lies tend to catch up :)

More More

String literal types are generally preferred :

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download