- Now in this video, we're gonna be talking
about a special type called the void type.
And it's gonna be a rather short video.
For example, if we hover over the sum,
you know that the return type of this sum function
is a number and that's because TypeScript infers that.
Or we can manually come in here and say
that the return type is going to be number if we want.
But what happens if a function
doesn't actually return anything?
Let's create a brand new function.
This one's just gonna be print name.
We're gonna pass it along a name which is a string
and it's just gonna console.log that name variable.
This function has no return at all.
So what is the return type?
Well, if we hover over print name,
you can see the return type is set to void.
We could also manually say
that this is going to be a void return, as well.
And all that means is that your function
has no return keyword and it doesn't return anything.
This is a slightly different keyword
than undefined, because in JavaScript, by default,
if you run a function and it doesn't return anything at all
it'll output undefined if you try to set a variable to it.
So if I just say const a equals print name,
pass it in a name,
this a variable is technically undefined
by JavaScript standards.
But in TypeScript, we actually differentiate
undefined from void functions
'cause they have a slightly different meaning to them.
When I say that a function returns nothing,
and by that I mean the return type is set to void,
I'm essentially saying that there is nothing you can do
with the return from this function.
It doesn't return anything and nothing that comes
from it is useful in any way at all.
While if I explicitly say
that the function returns undefined,
I can at least use that in my TypeScript code
because I know that this thing is now undefined
that it is returning from it.
It's like an explicit return type of undefined,
while void is just explicitly saying
this returns nothing at all
and it never will return anything at all.
So there's a slight difference between those two.
For example, if I were to just come in here
and I place a return statement, now when I look
at my print name, you can see it's still a void type.
'cause again, I'm returning nothing all from my function.
If I instead explicitly return undefined,
you can now see the return type
of this function has changed to undefined from void.
So if you want to return undefined
from a function and use it as undefined in TypeScript,
you need to manually return undefined.
But in 99% of cases, void is going to work just fine
'cause if you have a function
that you don't want to return anything from, or you are
returning early by just having the return statement,
it makes sense that this will be a void type
'cause essentially it's saying there's nothing there at all.