Skip to content

Instantly share code, notes, and snippets.

@Evanion
Created August 19, 2019 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Evanion/16aa7d59de83c61af46ed330410bf915 to your computer and use it in GitHub Desktop.
Save Evanion/16aa7d59de83c61af46ed330410bf915 to your computer and use it in GitHub Desktop.
StringEnum for Typescript
import StringEnum from './StringEnum';
export const Intent = StringEnum(['success', 'warning', 'error', 'info']);
export type Intent = keyof typeof Intent;
/**
* This allows you to declare an enum that can be used a both a type and value, while still allowing the user to use plain strings.
* The option to use plain strings is good when you are developing a library that might be used in a none TS project.
* example
````
const Message = (intent:Intent) => (message: string) => {
...
}
const SendWarningMessage = (message:string) => {
Message(Intent.warning)(message);
}
const SendSuccessMessage = (message:string) => {
Message('success')(message);
}
````
*/
export default function StringEnum<T extends string>(o: T[]): { [K in T]: K } {
return o.reduce((res, key) => {
res[key] = key;
return res;
}, Object.create(null));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment