I am working on developing a finite state machine companion for my chatbot automation library. The aim is to guide users towards different conversation phases while interacting with the bot.
The plan is for the users of the library to supply a "state machine descriptor" to a function that will then create an instance of the state machine.
Although all functionalities are operational, I am looking to enhance the static typing for users of the library.
My goal is to achieve the following:
const myStateMachine = createStateMachine({
initialState: "state1",
states: {
state1: {
onMessage: (requester: MessageObj, stateMachine: StateMachineInstance) => {
requester.reply("hello1");
stateMachine.setState("state2");
}
},
state2: {
onMessage: (requester: MessageObj, stateMachine: StateMachineInstance) => {
requester.reply("hello2");
stateMachine.setState("state1");
}
}
}
});
Presently, I am encountering an issue: the method stateMachine.setState("state2")
is accepting any string, rather than the specified state keys in the descriptor. It should only allow "state1" | "state2"
since those are the determined states of the state machine.
I have attempted various solutions, but most of them are resulting in TypeScript errors. As a temporary solution, I have reverted back to a generic string to ensure compilation.
These are the current type definitions:
type StateId = string;
type State =
{
onMessage: (
requester: MessageObj,
stateMachineInstance: StateMachineInstance
) => any;
}
type StateMachineDescriptor = {
initialState: StateId;
states: {
[stateId: string]: State,
}
};
type StateMachineInstance = StateMachineDescriptor & {
currentState: StateId;
setState: (newState: StateId) => void;
reset: () => void;
};