Reputation: 6590
While reading the TypeScript handbook, I came across the first sentence at the top of the page on enums:
Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript.
What does this mean? What is a type-level extension?
Upvotes: 1
Views: 519
Reputation: 1
I am of the understanding that 'type-level extension' refers to the fact that that TS, when stripped of types at runtime, is just JS code. So, it just extends JS with types.
Enums are the type and the value, so they have no types to be removed. The TS compiler, unusually, actually generates JS code that didn't exist in the TS code to account for that. Similarly to enums, TS does the same with Namespaces.
According to this article, and I've heard it elsewhere, enums should be avoided in favor of union types (and regular modules in place of namespaces)
Upvotes: 0
Reputation: 15323
TypeScript was designed from the ground up to be a superset of Javascript, with the intention to have no runtime impact.
The design goals document should give you a pretty good idea of what design principles TypeScript is based on.
Pretty much everything you write in TypeScript which has to do with types (another way to put it is, everything that wouldn't be valid JS syntax) is only used by tsc at compile time, but disappears at runtime.
enums
are an exception to that, as they actually result in some JS code being produced and used at runtime.
Upvotes: 2