Created
April 11, 2017 09:44
-
-
Save hejrobin/6e869684f5e493681d7e171d818b8802 to your computer and use it in GitHub Desktop.
This file contains 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
/* @flow */ | |
// The following three lines are from https://gist.github.com/nmn/b20a92e848c68d88f7fdb8353c71b1ca | |
type $Object<V> = { +[ key : string] : V } | |
type $ObjectValues<V, O : $Object<V>> = V | |
type $Values<O: Object> = $ObjectValues<*, O> | |
type Enumerables = { [ key : string ] : any } | |
const UserRoles : Enumerables = { | |
ADMIN: 1, | |
BASIC: 2, | |
MOD: 'MODERATOR', | |
BOT: 'I_R_A_PROGRAMZ' | |
} | |
type UserRole = $Values<typeof UserRoles> | |
class User { | |
currentRole : UserRole = UserRoles.BASIC | |
constructor( userRole : ?UserRole ) : void { | |
this.role = userRole | |
} | |
set role( newUserRole : ?UserRole ) : void { | |
if ( newUserRole ) { | |
this.currentRole = newUserRole | |
} | |
} | |
get role() : any { | |
// @NOTE Mind the any return type, as defined in Enumerables. | |
return this.currentRole; | |
} | |
} | |
const basicUser = new User() | |
console.log( basicUser.role === UserRoles.BASIC ) | |
// Alter just to test it out | |
basicUser.role = UserRoles.MOD | |
console.log( basicUser.role === UserRoles.MOD ) | |
const botUser = new User(UserRoles.BOT) | |
console.log( botUser.role === UserRoles.BOT ) | |
// @NOTE Magic |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Caveats
basicUser.role = 'some arbitrary value'
doesn't really trigger an error, flow annotations are in fact valid, so this is expected. Could be easily fixed by having a simple enum-validator inset role
.