I have the following code:
type Robot = RobotOn | RobotOff;
class RobotOn {
public readonly state = "on";
public speak() {
console.log("heyman!");
}
}
class RobotOff {
public readonly state = "off"
}
function maybeSpeak(robot: Robot) {
if (robot.state === "off") throw Error("robot can't speak when it's off!");
robot.speak();
}
Now I would love to assert the state of the robot with a typescript assertion function! So something like this:
function maybeSpeak(robot: Robot) {
assertRobotState(robot, "on");
robot.speak();
}
Is this even possible? And what would the assertRobotState
function look like?
Thanks!
You can use assertion based on type of an argument -
asserts <<arg>> is <<type>>
.References: