- Hands-On Functional Programming with TypeScript
- Remo H. Jansen
- 401字
- 2021-07-02 14:03:12
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.
- 多媒體CAI課件設(shè)計(jì)與制作導(dǎo)論(第二版)
- JBoss Weld CDI for Java Platform
- Reporting with Visual Studio and Crystal Reports
- 基于Java技術(shù)的Web應(yīng)用開發(fā)
- 64位匯編語(yǔ)言的編程藝術(shù)
- Raspberry Pi 2 Server Essentials
- Visual C#.NET程序設(shè)計(jì)
- Android系統(tǒng)級(jí)深入開發(fā)
- Windows Phone 7.5:Building Location-aware Applications
- Yii Project Blueprints
- 0 bug:C/C++商用工程之道
- 21天學(xué)通C++(第5版)
- JavaScript程序設(shè)計(jì)(第2版)
- Getting Started with Python
- Sails.js Essentials