Categories
TypeScript Answers

How to add switch statement for a specific type in TypeScript?

Spread the love

Sometimes, we want to add switch statement for a specific type in TypeScript.

In this article, we’ll look at how to add switch statement for a specific type in TypeScript.

How to add switch statement for a specific type in TypeScript?

To add switch statement for a specific type in TypeScript, we can add them as we do with JavaScript.

For instance, we write

interface Action {}

class SpecificAction implements Action {
  kind: "specific";
  payload?: any;
}

class ToggleAction implements Action {
  kind: "toggle";
  toggle: boolean;
}

let action: SpecificAction | ToggleAction;
switch (action.kind) {
  case "specific":
    console.log(action.payload);
    break;
  case "toggle":
    console.log(action.toggle);
    break;
}

to create the action variable that has the SpecificAction | ToggleAction.

So the kind, payload, and toggle values are all valid properties.

We compare the action.kind value with the values listed with case.

Conclusion

To add switch statement for a specific type in TypeScript, we can add them as we do with JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *