There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply () below.
If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.
Join the Discussion. Help a fellow learner on their journey.
Ask or answer a question about this exercise by clicking reply () below!
You can also find further discussion and get answers to your questions over in Language Help.
Agree with a comment or answer? Like () to up-vote the contribution!
Hey, a learner myself here so take what I say with a grain of salt.
The way I understand it is that the serve() and kick() methods of their respective types return no value but run an action.
As they are just types they represent the object they are annotated to and neither return a value nor perform an action themselves but instruct the method to expect no return value.
Meaning, that the sport argument needs to be pre-defined before it is run through the play() function.
As this is just given as an example in the exercise the code above does nothing functionally. For it to work you’d need to define a sport object (provide type of either Tennis or Soccer, or at least infer it) and run the function with said sport argument.
I.E.:
type Tennis = {
serve: () => void;
}
type Soccer = {
kick: () => void;
}
function play(sport: Tennis | Soccer) {
if ('serve' in sport) {
return sport.serve();
}
if ('kick' in sport) {
return sport. Kick();
}
}
const football: Soccer = {
kick() {
// action somehow related to kicking goes here i.e. a web page creates a <div>Ball Kicked!/div>
const kickDiv = document.createElement('div');
div.innerText = "Ball Kicked!";
parentElement.appendChild(kickDiv);
}
}
const tennis: Tennis = {
serve() {
// returns a value like the serve velocity
return Math.floor(Math.random*100);
}
}
// Then the following is correct:
play(football); // runs
play(tennis); // typeError as tennis.serve returns a value
}
Someone with more experience, please, do correct me if I’m wrong.
P.S. My answer comes 2 years later, but I had the same question and tried looking here but had to go through the TS docs to understand it. Now at least there is something go on