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

Function types

We already know that it is possible to explicitly declare the type of an element in our application by using optional type annotations:

function greetNamed(name: string): string {
return 'Hi! ${name}';
}

In the previous function, we specified the type of parameter name (string) and its return type (string). Sometimes, we will need to specify the types of the function, as opposed to specifying the types of its components (arguments or returned value). Let's look at an example:

let greetUnnamed: (name: string) => string;

greetUnnamed = function(name: string): string {
return 'Hi! ${name}';
};

In the preceding example, we have declared the greetUnnamed variable and its type. The greetUnnamed type is a function type that takes a string variable called name as its only parameter and returns a string after being invoked. After declaring the variable, a function, whose type must be equal to the variable type, is assigned to it.

We can also declare the greetUnnamed type and assign a function to it in the same line, rather than declaring it in two separate lines, as we did in the previous example:

let greetUnnamed: (name: string) => string = function(name: string): string {
return 'Hi! ${name}';
};

Just like in the previous example, the preceding code snippet also declares a variable, greetUnnamed, and its type. greetUnnamed  is a function type that takes a string variable called name as its only parameter and will return a string after being invoked. We will assign a function to this variable in the same line in which it is declared. The type of the assigned function must match the variable type.

In the preceding example, we have declared the type of the greetUnnamed  variable and then assigned a function as its value. The type of function can be inferred from the assigned function and, for this reason, it is unnecessary to add a redundant type annotation. We have done this to facilitate your understanding of this section, but it is important to mention that adding redundant type annotations can make our code harder to read, and is considered a bad practice.

主站蜘蛛池模板: 微山县| 连云港市| 博罗县| 天等县| 和龙市| 鄂尔多斯市| 岳西县| 庆安县| 南华县| 安吉县| 库车县| 博罗县| 扶风县| 滨州市| 喀喇| 大理市| 孝义市| 阳江市| 宜春市| 西乌| 通化市| 蓝田县| 澜沧| 巴彦淖尔市| 兴安县| 拜城县| 新绛县| 册亨县| 尖扎县| 大港区| 丹阳市| 右玉县| 靖安县| 平昌县| 辰溪县| 孝昌县| 双峰县| 霍邱县| 讷河市| 前郭尔| 昌都县|