The `void` Type
Like before, we can start by annotating the listener
parameter to be a function. For now, we'll specify that it returns a string:
const addClickEventListener = (listener: () => string) => { document.addEventListener("click", listener);};
The problem is that we now have an er
Transcript
00:00 Okay, so here's the challenge then. If we give this a function type, and let's say we get it to return String, then this isn't good, really, because we're now going to get an error when we use this because this is saying type void is not assignable to type String.
00:18 Hmm. If we just extract out this function here, and we just say const Listener is this, and let's say we pull Listener back in there, and we hover over Listener here, you can see that this is a function that returns void.
00:33 Hmm. If we actually just manually return undefined here, then it's actually going to say, okay, now it's returning undefined. But when it returns nothing, it returns void. So let's just try trying out that void up here. Okay, now it's working.
00:49 So void in TypeScript is basically a way of saying, let's say we just had a result equals Listener here, and we hover over Listener, or hover over result rather, we can see that this is void. So this isn't undefined, which is actually what it would be in JavaScript, right? Because if you were to run this in JavaScript, result would be undefined.
01:07 But TypeScript has this special void type. And what void says is basically nothing is ever going to be here. Not the value of undefined, but nothing, nothing, nothing, nothing. So void is a really nice, useful type for these situations where we want our function to return nothing.
01:26 I think they relaxed some rules here. So return null is absolutely fine. You can actually return anything you want from this. But the point is that it will be ignored by the output. So void is really useful for listeners, for any sort of function which does a side effect or anything like that,
01:45 where you basically don't care about the output of the function. And void is really, really nice for these situations.