Created
November 28, 2017 20:03
-
-
Save OliverJAsh/7176b51c454f4d25448fb1ed2fa976ae to your computer and use it in GitHub Desktop.
TypeScript enums at the type and value level
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
{ | |
// Enums represent types and values | |
// At the type level, this is a union of all enum members | |
// At the value level, this is an object containing enum members | |
enum TypeEnum { | |
foo, | |
bar, | |
baz, | |
} | |
// To access the object type of an enum, we use `typeof <value>`, where `<value>` is the enum | |
// object value. | |
type TypeObject = typeof TypeEnum; | |
// Type level | |
type MyObject = { | |
// Union of all enum members | |
type: TypeEnum; | |
// Object containing enum members | |
types: TypeObject; | |
}; | |
// Value level | |
const myObject: MyObject = { | |
// Single enum member | |
type: TypeEnum.bar, | |
// Object containing enum members | |
types: TypeEnum, | |
}; | |
// As well as being able to express the type of the enum object from the enum, we can also go the | |
// other way: express the type of the enum union from the enum object. Example: | |
type ObjectKeys<Object> = Object[keyof Object]; | |
type TypeEnumFromObject = ObjectKeys<TypeObject>; | |
const myType: TypeEnumFromObject = TypeEnum.bar; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment