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

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.

主站蜘蛛池模板: 新巴尔虎左旗| 蛟河市| 曲水县| 东乡| 华坪县| 洛南县| 赤水市| 阜宁县| 炉霍县| 平南县| 高平市| 克山县| 泰来县| 峨山| 南岸区| 溧阳市| 姜堰市| 扎鲁特旗| 柳河县| 霞浦县| 高邑县| 萨迦县| 万载县| 肃北| 永仁县| 楚雄市| 禄劝| 会宁县| 阿合奇县| 应城市| 枣庄市| 肥西县| 大竹县| 聊城市| 钦州市| 莱芜市| 策勒县| 灵川县| 遂平县| 绍兴市| 高雄县|