|
|
|
|
|
by zdragnar
1353 days ago
|
|
Now try this: type MyEnum = 'a' | 'b' | 'c';
function test(val: MyEnum) {
return val;
}
// refactors
test('a');
// does not refactor
const testVal = 'a';
test(testVal);
The simple fact is that- as far as the type system is concerned, enums are more than simple strings, and they are useful for those differences.As for the readability, it gets a little more interesting when you are interacting with libraries or APIs outside of your control; you end up with hyphenated things, underscored, and other oddities that may not be a one-to-one match between a logical, easily readable key and the underlying value it represents. |
|
Sure- the auto-refactor won't work here, only the typecheck, and that's the desired behavior in this case because the intended use of 'a' is not necessarily known at that point in the code. Which is the point you're making I guess, though I have to say, in practice this is an unusual case that I never really see; usually if I'm creating an enum-string it's directly in a function call, typed object literal, etc.
> as far as the type system is concerned, enums are more than simple strings
I was surprised to find you were right about this; I expected the above to pass checks, but it doesn't. TypeScript actually does treat the enum as more than just its underlying value. So that's interesting- and that's the first reason I've really seen to use theseBut I think I still prefer plain values, for myself. There's just something that feels right and pure about using plain JSON-like JavaScript values, and then overlaying types on top of them that have no effect on their behavior and don't obscure their underlying representation. You know exactly what you've got, it's maximally duck-typeable, it's unchanged when it gets (de)serialized, it all just feels better to me