Managing Task Status Transitions in TypeScript with Enums and Object Mapping

m4r14

mark vachi

Posted on December 21, 2022

Managing Task Status Transitions in TypeScript with Enums and Object Mapping

An enum in TypeScript can be used to represent the possible states of a task, as shown in the following graph:

Image description

We can use a function and an object mapping to manage transitions between these states.

enum TaskStatus {
  NONE,
  ACCEPT,
  MEET,
  REACH,
  COMPLETE,
  CANCEL
}

const transitionMap: { [key in TaskStatus]: TaskStatus[] } = {
  [TaskStatus.NONE]: [TaskStatus.ACCEPT, TaskStatus.CANCEL],
  [TaskStatus.ACCEPT]: [TaskStatus.MEET, TaskStatus.CANCEL],
  [TaskStatus.MEET]: [TaskStatus.REACH, TaskStatus.CANCEL],
  [TaskStatus.REACH]: [TaskStatus.COMPLETE, TaskStatus.CANCEL]
};

const transition = (currentStatus: TaskStatus, nextStatus: TaskStatus): boolean => {
  return transitionMap[currentStatus].includes(nextStatus);
}
Enter fullscreen mode Exit fullscreen mode

To define the valid transitions for each status, we can use an object mapping. The object keys are the current statuses, and the values are arrays of valid next statuses. We can then use the includes method to check if the desired next status is in the list of valid transitions for the current status.

Here's an example of using the transition function to check if a transition is valid:

const isValid = transition(TaskStatus.MEET, TaskStatus.REACH); // true
const isInvalid = transition(TaskStatus.MEET, TaskStatus.NONE); // false
Enter fullscreen mode Exit fullscreen mode

Using this approach, we can easily manage the status transitions for our tasks and ensure that they are being updated correctly. This can be especially useful in larger projects where there may be many different states and transitions to track.

💖 💪 🙅 🚩
m4r14
mark vachi

Posted on December 21, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related