TypeState
TypeState is a strongly typed finite state machine for TypeScript or JavaScript. Finite state machines are useful for modeling complicated flows and keeping track of state.
Installation
Install-Package TypeState
npm install typestate
bower install typestate
Basic Example
// Let's model the states of an elevator // Define an Enum with all possible valid statesenum Elevator DoorsOpened DoorsClosed Moving // Construct the FSM with the inital state, in this case the elevator starts with its doors openedvar fsm = <Elevator>ElevatorDoorsOpened; // Declare the valid state transitions to model your system // Doors can go from opened to closed, and vice versafsm;fsm; // Once the doors are closed the elevator may movefsm; // When the elevator reaches its destination, it may stop movingfsm; // Check that the current state is the initial stateiffsm console; // Test validity of transitions from the current state, in this case 'Elevator.DoorsOpened'fsm; // returns truefsm; //returns false // Go to a new state, closing the elevator doors. fsm; // The fsm.currentState is now set to 'Elevator.DoorsClosed' // The elevator can now move or open the doors againfsm; // returns truefsm; //returns true
Using JavaScript
JavaScript is easy with TypeState. The finite state machine relies on states that can be converted to strings with the .toString()
method. So to use JavaScript simple replace the top few lines of the previous example with the following:
var Elevator = DoorsOpened : "DoorsOpened" DoorsClosed : "DoorsClosed" Moving : "Moving" var fsm = ElevatorDoorsOpened
Listening for state changes
TypeState allows you to listen to state changes. For example if the elevator starts moving, we would like to play some elevator music. Additionally we would like to stop the music when the elevator stops.
fsm; fsm;
Interrupting Transitions
Sometimes you need to interrupt transitions. You may interrupt transitions to a state with onEnter(STATE, CALLBACK)
and interrupt transitions from a state with the onExit(STATE, CALLBACK)
. If the CALLBACK
returns false the transition is canceled and the state will not change.
console; // truevar handsInDoor = true; // Listen for transitions to DoorsClosed, if the callback returns false the transition is canceled.fsm; // Attempt to transitionfsm; // State does not change to DoorsClosedconsole; //true
Wildcard Transitions
If all transitions to or from a certain state are valid, there are a convience wildcard methods fromAny(STATE_ENUM)
and toAny(STATE_ENUM)
for such cases.
enum ValidStates A B C D var newFsm = <ValidStates>ValidStatesA;newFsm;newFsm;