type Direction = "up" | "down"; type Direction = "up" | "down";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
const types = ['x', 'y', 'z'] as const;
const a: typeof types[number] = 'a'; // not ok
const b: typeof types[number] = 'z'; // ok 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#cons...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.
const test(direction: Direction) => direction;
test('up' as 'up');
But now that I'm testing in typescript playground, I no longer need to write the "as" part — simply `test('up');` works fine as well.I wonder if you've seen this quirk of typescript before.
It's when you do
const dir = "up"; // TS infers type "string"
test(dir); // error
For mutable variables (let/var), you usually want TS to infer `string` in the first line. IMO the fact that they also infer `string` for constants is a design flaw, that I hope will one day be fixed.They recently added a feature to make this less painful:
const dir = "up" as const;
test(dir); // works
That's the same as `as "up"` bit without having to duplicate the string.(example in typescript playground: https://www.typescriptlang.org/play/#code/C4TwDgpgBAIglgJwgY...)