Nisha Patel
Problem
The idea is to create a finite state machine helper for my chatbot automation library so that the people talking to the bot can progress through different phases of a conversation.
I want the consumer of the library to provide a "state machine descriptor" to a function that would instantiate the state machine.
All the behavior is already working. I just want to improve the static typing for the consumers of the library.
This is what I want to accomplish:
Here is the problem I'm facing: the method stateMachine.setState("state2") accepts any string, not just the keys of the states provided in the descriptor. It should accept "state1" | "state2" because those are the states that the state machine would have.
I've tried a bunch of different things but most of them result in a typescript error. I just reverted those back to a generic string so that it would compile.
Here is what the types look like at the moment:
Solution
Here is my entire thought process behind writing a possible solution:
Since we need generics to solve this, I'll go ahead and write the signature of the function using one:
While you could probably make it work with States being an object type, having it represent the state names is a lot easier to work with. The first problem we encounter is TypeScript inferring States from the wrong place. If we write something like this:
Then TypeScript will infer States from initialState, which is wrong since we want initialState to be based on states, not the other way around. We can prevent inference on initialState using a trick to move it down the list of possible inference sites:
Blocking inference at initialState, it works as intended:
That was really the main problem here. Now all we have to do is add in a generic parameter:
Suggested blogs:
>How to Select checkboxes on an HTML treeview with JavaScript?
>How to use querySelectorAll()" with multiple conditions in JavaScript?
>How to fix mouseover event glitch in JavaScript?
>How to do light and dark mode in a website using HTML and JavaScript?
>How to manipulate manipulating Array object in JavaScript?
>How to merge an object into Array with the same key in JavaScript?
>Javascript Error Solved: Property 'id' does not exist on type 'T'
>Why highlighted table row using class not working in JavaScript?
>How to rename an object key based on the condition in JavaScript?
>How to sort an array based on another array in Javascript?
>Javascript: Modal not closing with a button