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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enum as generic #213

Closed
nandorojo opened this issue Mar 5, 2021 · 1 comment
Closed

Enum as generic #213

nandorojo opened this issue Mar 5, 2021 · 1 comment

Comments

@nandorojo
Copy link

nandorojo commented Mar 5, 2021

馃崺 Feature Request

Is there a way to use an enum as a generic?

Describe the solution you'd like

Say that I have an enum, and I want to set the color for each enum value.

enum Status {
  ACTIVE,
  PENDING
}

enumColors(Status, { [Status.ACTIVE]: 'red' })

Is there a way to do this dynamically based on a generic for the enum?

Describe alternatives you've considered

I tried this:

declare function enumColors<Key extends string, Value extends string, Enum extends { [key in Key]: Value }>(
  enumeration: Enum,
  colors: { [key in Key]?: string }
)

Playground link here.

Teachability, Documentation, Adoption, Migration Strategy

This is the error I see:

Screen Shot 2021-03-05 at 2 09 23 PM

@nandorojo
Copy link
Author

nandorojo commented Mar 5, 2021

Ah, the solution was to use the value, not key:

declare function enumColors<Key extends string, Value extends string, Enum extends { [key in Key]: Value }>(
  enumeration: Enum,
  colors: { [value in Value]?: string } // Value, not Key
)

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

No branches or pull requests

1 participant