- Hands-On Full Stack Web Development with Angular 6 and Laravel 5
- Fernando Monteiro
- 178字
- 2021-07-23 19:18:49
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:

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.
推薦閱讀
- 社交網(wǎng)絡(luò)對(duì)齊
- 物聯(lián)網(wǎng)標(biāo)準(zhǔn)化指南
- 高校網(wǎng)絡(luò)道德教育研究
- 面向物聯(lián)網(wǎng)的CC2530與傳感器應(yīng)用開(kāi)發(fā)
- SEO 20日
- Django 2 by Example
- 網(wǎng)絡(luò)故障現(xiàn)場(chǎng)處理實(shí)踐(第4版)
- Mastering TypeScript 3
- AWS Lambda Quick Start Guide
- 一本書(shū)讀懂TCP/IP
- 5G非正交多址接入技術(shù):理論、算法與實(shí)現(xiàn)
- 智慧城市中的物聯(lián)網(wǎng)技術(shù)
- 信息技術(shù)安全評(píng)估準(zhǔn)則:源流、方法與實(shí)踐
- NB-IoT原理和優(yōu)化
- 互聯(lián)網(wǎng)安全的40個(gè)智慧洞見(jiàn)(2018)