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

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.

主站蜘蛛池模板: 彭山县| 呼图壁县| 东阳市| 基隆市| 区。| 固镇县| 孝昌县| 朝阳市| 新闻| 辽阳县| 扎鲁特旗| 静海县| 天柱县| 金堂县| 芒康县| 东兰县| 南阳市| 侯马市| 西昌市| 阿坝| 仙桃市| 兴安盟| 金乡县| 长治市| 湛江市| 凤凰县| 临夏市| 郸城县| 和静县| 娄底市| 车致| 郎溪县| 八宿县| 博乐市| 金湖县| 昌江| 黔南| 镇康县| 望江县| 葫芦岛市| 广东省|