官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 汕头市| 通河县| 英山县| 贡觉县| 满城县| 达尔| 皮山县| 清水河县| 沛县| 临泉县| 抚顺县| 容城县| 阳东县| 微山县| 涡阳县| 佛学| 自治县| 杭锦后旗| 额敏县| 汕尾市| 河北区| 云霄县| 紫阳县| 宿州市| 建阳市| 东山县| 金溪县| 子洲县| 饶河县| 潼南县| 公安县| 永仁县| 阿拉善右旗| 两当县| 安泽县| 张家界市| 关岭| 彭阳县| 普兰店市| 清流县| 浠水县|