Skip to content

Instantly share code, notes, and snippets.

@hejrobin
Created April 11, 2017 09:44
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hejrobin/6e869684f5e493681d7e171d818b8802 to your computer and use it in GitHub Desktop.
Save hejrobin/6e869684f5e493681d7e171d818b8802 to your computer and use it in GitHub Desktop.
/* @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
@hejrobin
Copy link
Author

hejrobin commented Apr 11, 2017

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 in set role.

const ValidUserRole : Function = ( expectedUserRole : any ) : Bool => Object.values(UserRoles).includes(expectedUserRole)

class User {

  set role( newUserRole : ?UserRole ) : void {
    if ( newUserRole !== undefined && ValidUserRole(newUserRole) ) {
      this.currentRole = newUserRole
    }
  }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment