![Hands-On Full Stack Web Development with Angular 6 and Laravel 5](https://wfqqreader-1252317822.image.myqcloud.com/cover/587/36699587/b_36699587.jpg)
上QQ阅读APP看书,第一时间看更新
Using the void type
In TypeScript, it is mandatory to define the type of the return of a function. When we have a function that does not have a return, we use a type called void.
Let's see how it works:
Create a new file called void.ts inside the chapter-02 folder, and add the following code:
function myVoidExample(firstName: string, lastName: string): string {
return firstName + lastName;
}
console.log(myVoidExample('Jhonny ', 'Cash'));
In the preceding code, everything is OK, because our function returns a value. If we remove the return function, we will see the following error message:
void.ts(1,62): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value.
In VS Code, you would see the following:
![](https://epubservercos.yuewen.com/0CA4EE/19470390208868306/epubprivate/OEBPS/Images/1c7652c8-7333-4dbd-a38e-9247c6f90b4a.png?sign=1738838045-IlrSW7XuIhs9Tx02MzQXyGNoMXAJQemh-0-026491acbe1b3072fd3f96f69d18709f)
VS Code output error
To fix it, replace the type string with void:
function myVoidExample(firstName: string, lastName: string): void {
const name = firstName + lastName;
}
This is very useful, because our functions do not always return a value. But remember, we cannot declare void in functions that do return a value.