Skip to content

Instantly share code, notes, and snippets.

@bradleyayers
Created May 25, 2018 00:05
Show Gist options
  • Save bradleyayers/ca0e5648a0f6889ea89c34c33fd6bad5 to your computer and use it in GitHub Desktop.
Save bradleyayers/ca0e5648a0f6889ea89c34c33fd6bad5 to your computer and use it in GitHub Desktop.
Example of a type safe finite-state-machine API in TypeScript.
interface StateOne {
type: "one";
prevName?: string;
}
interface StateTwo {
type: "two";
name?: string;
}
type State = StateOne | StateTwo;
const two: StateTwo = { type: "two" };
const createWrapper = fsm<State>()({
one: {
toStateTwo: () => ({ type: "two" }),
toStateTwoWithName: (_, opts: { name: string }) => ({ type: "two", name: opts.name })
},
two: {
toStateOne: prevState => ({ type: "one", prevName: prevState.name })
}
});
const wrappedTwo = createWrapper({ type: "two", name: "davina" });
const wrappedOne = wrappedTwo.to.toStateOne();
wrappedOne.to.toStateTwo();
wrappedOne.to.toStateTwoWithName({ name: "brad" });
const wrappedState = createWrapper({ type: "one" } as State);
type WrappedState = typeof wrappedState;
if (wrappedState.type === "two") {
wrappedState.to.toStateOne()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment