as enum
assertion for object literals
#60790
Labels
Awaiting More Feedback
This means we'd like to hear from more people who would be helped by this feature
Suggestion
An idea for TypeScript
π Search Terms
enum, object literal, type-stripping
β Viability Checklist
Context
While TypeScript already allows declaring runtime enums values:
This is not standard JavaScript, and does not work in Node.js unless
--experimental-transform-types
is passed.An alternative "pure JS" pattern from the TypeScript handbook is:
https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums
There are two downsides to this pattern:
typeof X[keyof typeof X]
is both verbose and not beginner friendly.β Suggestion
Introduce some new syntax to TypeScript to help with the object-literal-as-enum pattern.
For example would be allowing
as enum
:(from #59658)
An alternative design could be allowing an
enum
type annotation onconst
variable declarationsexport const Compass: enum = {...}
.This annotation would effectively be the same as writing:
Rules
The
enum
annotation would only be permitted for object literals that arei.e. the object literal would follow very similar rules that are applied to
const enum C {}
syntaxBenefits
enum
Downsides
While this object literal as enum pattern is popular in codebases that avoid non-standard runtime syntax it does not have all the features available with
enum
syntax such as self-reference during construction.__proto__: null
is currently not supported #38385 making it difficult to avoid object literals from inheriting non-enum properties resulting in false positives withkey in MyEnum
.π Motivating Example
The above module will work out-of-the-box in Node.js (assuming nodejs/typescript#17).
π» Use Cases
Creating an enum like value using standard Object literal syntax with some of the type system benefits that
enum
syntax has.typeof Foo[keyof typeof Foo]
is not beginner friendly and is not a nominal typeOne workaround is to have a small utility for emulating an enum like nominal type from an object literal (playground). The
"literal" & { __key__: val }
trick works but results in noisey types when displayed to the developer (e.g. in an error message)The text was updated successfully, but these errors were encountered: