Functions, Lambdas, and Execution Flow
Learn about functions, lambdas, and execution flow in TypeScript.
Functions are the processing machines we use to analyze input, digest information, and apply the necessary transformations to data. Data can be provided either to transform the state of our application or return an output that will be used to shape our application’s business logic or user interactivity.
Functions in TypeScript are not that different from regular JavaScript, except that, like everything else in TypeScript, they can be annotated with static types. Therefore, they improve the compiler by providing the information it expects in their signature and the data type it aims to return, if any.
Annotating types in functions
The following example showcases how a regular function is annotated in TypeScript:
function sayHello(name: string): string {return 'Hello, ' + name;}
There are two main differences from the usual function syntax in regular JavaScript. First, we annotate the parameters declared in the function signature, which makes sense since the compiler will want to check whether the data provided holds the correct type. In addition to this, we also annotate the returning value by adding the string
type to the function declaration.
As mentioned previously, the TypeScript compiler is smart enough to infer types when no annotation is provided. In this case, the compiler looks into the arguments provided and returns statements to infer a returning type from them.
Functions in TypeScript can also be represented as expressions of anonymous ...