What is void?

A void is a special and is used mainly for a function that returns no value. With an explicit return to void, the function cannot accept a return statement with a value that can occur with it; hence, it acts as a guard of potential error of returning a value. A void function can still have an empty return to leave the function before reaching the closing curly bracket. A void variable can only be assigned to undefined:

let a: void = undefined;
console.log(a);

This is not useful, but it explains what happens if you return a function without a value to a void function:

function returnNothing():void{
return;
}
console.log(returnNothing()); // undefined

It is always a good practice to mark a function with void instead of using the implicit return value. The implicit return type for a function is a weak void because the function allows the returning of anything. The following function doesn't have a return type and was initially returning nothing. However, in its life, the function changed (as you will see next) and now returns three different values that are not like the previous ones. The implicit returns value is not void anymore. Having an explicit return type define a contract and indicate to anyone touching the function what is the expected return type and that should be respected. In this example code, the function returns a union of a Boolean, number, and string:

function returnWithoutType(i: number) {
if (i === 0) {
return false;
} else if (i < 0) {
return -1;
} else {
return "positive";
}
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.70.21