Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This fixes #5. It is more or less a merging of the original implementation of this module and the example provided by @weswigham. The problem exhibited by
WeirdEnum
is solved by giving the function two type parameters, both of which are inferred by the TypeScript compiler. Additionally, theforEach
call was replaced withfor-of
to allow this module to work even in an ES3 environment with no need for an ES5Array.prototype.forEach
polyfill.There is still some room for improvement:
keyof
to a non-object type. For instance, giventype Enum<T> = T[keyof T]
, one can writeEnum<number>
and not fail compilation. (The result is harmless, although meaningless:number
.) If we raise the TypeScript dependency of this module from 2.1 to 2.2, we can use theobject
type as a constraint:type Enum<T extends object> = T[keyof T]
.Object.keys
andObject.values
to be used with these enum types. For example, givenconst e = {a: 'A', b: 'B'}
,Enum.keys(e)
should yield('a' | 'b')[]
(instead ofstring[]
likeObject.keys
does) andEnum.values(e)
should yield('A' | 'B')[]
(instead ofany[]
likeObject.values
does).I believe this also solves #7, so long as you define an enum using the extended form:
Rather than the short form: