Created
August 19, 2019 12:50
-
-
Save Evanion/16aa7d59de83c61af46ed330410bf915 to your computer and use it in GitHub Desktop.
StringEnum for Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
```` | |
*/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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