- 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.
推薦閱讀
- CorelDRAW X6 中文版圖形設(shè)計(jì)實(shí)戰(zhàn)從入門到精通
- 重新定義Spring Cloud實(shí)戰(zhàn)
- 互聯(lián)網(wǎng)安全的40個(gè)智慧洞見(jiàn):2015年中國(guó)互聯(lián)網(wǎng)安全大會(huì)文集
- 物聯(lián)網(wǎng)時(shí)代
- 計(jì)算機(jī)網(wǎng)絡(luò)與通信(第2版)
- 光纖通信系統(tǒng)與網(wǎng)絡(luò)(修訂版)
- SAE原理與網(wǎng)絡(luò)規(guī)劃
- 4G小基站系統(tǒng)原理、組網(wǎng)及應(yīng)用
- 夢(mèng)工廠之材質(zhì)N次方:Maya材質(zhì)手冊(cè)
- 網(wǎng)管第一課:網(wǎng)絡(luò)操作系統(tǒng)與配置管理
- 云工廠:開(kāi)啟中國(guó)制造云時(shí)代
- 深入理解計(jì)算機(jī)網(wǎng)絡(luò)
- 物聯(lián)網(wǎng)
- 加密與解密實(shí)戰(zhàn)全攻略
- 網(wǎng)絡(luò)安全和信息化黨政領(lǐng)導(dǎo)干部一本通