Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Differing enum values #9

Merged
merged 2 commits into from
Mar 23, 2017
Merged

Conversation

kourge
Copy link
Contributor

@kourge kourge commented Mar 23, 2017

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, the forEach call was replaced with for-of to allow this module to work even in an ES3 environment with no need for an ES5 Array.prototype.forEach polyfill.

There is still some room for improvement:

  • TypeScript does not prohibit you from applying keyof to a non-object type. For instance, given type Enum<T> = T[keyof T], one can write Enum<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 the object type as a constraint: type Enum<T extends object> = T[keyof T].
  • Introduce type-safe variants of Object.keys and Object.values to be used with these enum types. For example, given const e = {a: 'A', b: 'B'}, Enum.keys(e) should yield ('a' | 'b')[] (instead of string[] like Object.keys does) and Enum.values(e) should yield ('A' | 'B')[] (instead of any[] like Object.values does).

I believe this also solves #7, so long as you define an enum using the extended form:

export const Status = Enum({
  /**
   * The service is running and operational
   */
  RUNNING: 'running',

  /**
   * Something is wrong
   */
  STOPPED: 'stopped',
});
export type Status = Enum<typeof Status>;

Rather than the short form:

export const Status = Enum('running', 'stopped');
export type Status = Enum<typeof Status>;

@dphilipson
Copy link
Owner

dphilipson commented Mar 23, 2017

This is fantastic, thank you very much for this contribution!

@dphilipson dphilipson merged commit 512de2d into dphilipson:master Mar 23, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Different keys and values
2 participants