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

Named and anonymous functions

Just as in JavaScript, TypeScript functions can be created either as a named function or as an anonymous function, which allows us to choose the most appropriate approach for an application, whether we are building a list of functions in an API or a one-off function to hand over to another function:

// named function
function greet(name?: string): string {
if(name){
return "Hi! " + name;
} else {
return "Hi!";
}
}

// anonymous function
let greet = function(name?: string): string {
if (name) {
return "Hi! " + name;
} else {
return "Hi!";
}
}

As we can see in the preceding code snippet, in TypeScript, we can add types to each of the parameters and then to the function itself to add a return type. TypeScript can infer the return type by looking at the return statements, so we can also optionally leave this off in many cases.

There is an alternative syntax for functions that use the => operator after the return type and don't use the function keyword:

let greet = (name: string): string => {
if(name){
return "Hi! " + name;
}
else
{
return "Hi";
}
};

Now that we have learned about this alternative syntax, we can return to the previous example in which we were assigning an anonymous function to the greet variable. We can now add type annotations to the greet variable to match the anonymous function signature:

let greet: (name: string) => string = function(name: string): 
string {
if (name) {
return "Hi! " + name;
} else {
return "Hi!";
}
};

Keep in mind that the arrow function (=>) syntax changes the way the this operator works when working with classes. We will learn more about this in upcoming chapters.

The previous code snippet demonstrates how to use type annotations to force a variable to be a function with a specific signature. These kinds of annotation are commonly used when we annotate a callback (a function used as an argument of another function):

function add(
a: number,
b: number,
callback: (result: number) => void
) {
callback(a + b);
}

In the preceding example, we are declaring a function named add that takes two numbers and a callback as a function. The type annotations will force the callback to return void and take a number as its only argument.

主站蜘蛛池模板: 和平区| 永城市| 乐昌市| 平乡县| 家居| 朔州市| 双辽市| 天祝| 故城县| 天气| 惠东县| 宁津县| 萍乡市| 安达市| 定西市| 黔西县| 利辛县| 中江县| 安国市| 博兴县| 镇坪县| 竹山县| 和硕县| 青岛市| 博乐市| 牙克石市| 旺苍县| 裕民县| 彭阳县| 花莲县| 右玉县| 芮城县| 淮南市| 阿巴嘎旗| 太仓市| 栖霞市| 大邑县| 镇原县| 肥西县| 古田县| 屏山县|