3 ms·
Enums and string literals aren't completely interchangable. Enums are transpired to objects so you can iterate the keys/values. You can't do that with SL which
by redact207 7y ago
Enums and string literals aren't completely interchangable.
Enums are transpired to objects so you can iterate the keys/values. You can't do that with SL which are a transpiler feature only.
Also you can't codedoc string literal values like you can with enums where it shows up with intellisense.
I tend to prefer enums as a result
- reaktivo 7y agoSince TS 3.4 you can have enum-like behaviour by using the `as const` annotation on object and array literals. const types = ['x', 'y', 'z'] as const; const a: typeof types[number] = 'a'; // not ok const b: typeof types[number] = 'z'; // ok
- styfle 7y agoNot to be confused with `const enum` which act more like a preprocessor and emits in the value at compile time. const enum Directions { Up, Down, Left, Right } console.log(Directions.Left) // emits js file with console.log(2) https://www.typescriptlang.org/docs/handbook/enums.html#const-enums https://www.typescriptlang.org/docs/handbook/enums.html#cons...
- munchor 7y agoThat is correct. However, I still prefer using union types so that I'm not locked in to TypeScript. By using only union types as "enums" and never using enums or namespaces, I guarantee that all the TS-specific code I write can be erased and if I ever were to use just JavaScript in the future, I could. Also, I use Babel to transpile TS to ES3.
- reaktivo 7y agoYou can have the best of both worlds, see this comment https://news.ycombinator.com/item?id=21134911 https://news.ycombinator.com/item?id=21134911
- deleted 7y ago[deleted]