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.