TypeScript Functions
A function is a group of statements that together perform a task.
You can divide your code into different functions. How to divide the code among different functions is up to you, but logically, division is usually based on each function performing a specific task.
A function declaration tells the compiler the function's name, return type, and parameters. The function definition provides the actual body of the function.
Function Definition
A function is a block of code wrapped in curly braces, preceded by the keyword function:
The syntax is as follows:
function function_name()
{
// 执行代码
}
Example
TypeScript
Calling a Function
A function can only execute the code inside it when it is called.
The syntax is as follows:
function_name()
Example
TypeScript
Function Return Value
Sometimes we want a function to return the result of its execution to the place where it was called.
This can be achieved by using the return statement.
When a return statement is used, the function stops executing and returns the specified value.
The syntax is as follows:
function function_name():return_type {
// 语句
return value;
}
return_type is the type of the return value.
The return keyword is followed by the result to be returned.
In general, a function has only one return statement.
The type of the returned value must be consistent with the return type (return_type) defined in the function.
Example
TypeScript
In the example, a function is definedgreet(), and the return type is string.
greet()The function returns to the place where it was called via the return statement, i.e., the variable msg, and then outputs the return value.
Compile the above code to get the following JavaScript code:
JavaScript
Functions with Parameters
When calling a function, you can pass values to it, and these values are called parameters.
These parameters can be used within the function.
You can send multiple parameters to a function, with each parameter separated by a comma,:
The syntax is as follows:
function func_name( param1 [:datatype], param2 [:datatype]) {
}
param1 and param2 are parameter names.
datatype is the parameter type.
Example
TypeScript
In the example, a function is definedadd(), and the return type is number.
add()The function defines two parameters of type number, and adds the two parameters and returns the result.
Compile the above code to get the following JavaScript code:
JavaScript
The output is:
3
Optional and Default Parameters
Optional Parameters
In TypeScript functions, if we define parameters, we must pass these parameters unless we set them as optional. Optional parameters are marked with a question mark ?.
Example
TypeScript
In the following example, we set lastName as an optional parameter:
TypeScript
Optional parameters must follow required parameters. If in the above example we want firstName to be optional and lastName to be required, then we need to adjust their positions and put firstName last.
It doesn't matter if all parameters are optional.
Default Parameters
We can also set default values for parameters, so that when calling the function, if the parameter value is not passed, the default parameter is used. The syntax is:
function function_name(param1[:type],param2[:type] = default_value) {
}
Note: A parameter cannot be set as both optional and default.
Example
In the following example, the function's parameter rate is set to a default value of 0.50. When the function is called without passing the parameter, the default value is used:
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output is:
计算结果: 500 计算结果: 300
Rest Parameters
There is a situation where we don't know how many parameters to pass to a function. In such cases, we can use rest parameters to define it.
Rest parameter syntax allows us to pass an indefinite number of parameters as an array.
TypeScript
The last named parameter of the function, restOfName, is prefixed with ..., and it becomes an array consisting of the remaining parameters, with index values from 0 (inclusive) to restOfName.length (exclusive).
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output is:
和为: 6 和为: 50
Anonymous Functions
An anonymous function is a function without a function name.
Anonymous functions are dynamically declared at program runtime. Apart from not having a function name, they are the same as standard functions.
We can assign an anonymous function to a variable, and such an expression becomes a function expression.
The syntax is as follows:
var res = function( [arguments] ) { ... }
Example
Anonymous function without parameters:
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output is:
hello world
Anonymous function with parameters:
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output is:
24
Self-invoking Anonymous Functions
An anonymous function can be self-invoked by using () after the function:TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output is:
Hello!!
Function Constructor
TypeScript also supports using JavaScript's built-in constructor Function() to define functions:
The syntax is as follows:
var res = new Function ([arg1[, arg2[, ...argN]],] functionBody)
Parameter description:
- arg1, arg2, ... argN: A list of parameters.
- functionBody: A string containing JavaScript statements that include the function definition.
Example
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output is:
12
Recursive Functions
A recursive function is a function that calls itself within the function.For example:
Once upon a time there was a mountain, in the mountain there was a temple, in the temple there was an old monk telling a story to a little monk! What was the story? "Once upon a time there was a mountain, in the mountain there was a temple, in the temple there was an old monk telling a story to a little monk! What was the story? 'Once upon a time there was a mountain, in the mountain there was a temple, in the temple there was an old monk telling a story to a little monk! What was the story? …'"
Example
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output is:
720
Lambda Functions
Lambda functions are also called arrow functions.
Arrow function expressions have a shorter syntax than function expressions.
A function with only one statement:
( [param1, param2,…param n] )=>statement;
Example
The following example declares a lambda expression function that returns the sum of two numbers:TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output is:
110
A function is a statement block:
( [param1, param2,…param n] )=> {
// 代码块
}
Example
The following example declares a lambda expression function that returns the sum of two numbers:
TypeScript
Compiling the above code produces the following JavaScript code:
JavaScript
The output is:
110We don't need to specify the parameter types; the types are inferred within the function:
TypeScript
Compiling the above code produces the following JavaScript code:
JavaScript
The output is:
12 是一个数字 Tom 是一个字符串
Single parameter()is optional:
TypeScript
Compiling the above code produces the following JavaScript code:
JavaScript
The output is:
输出为 12
When there are no parameters, empty parentheses can be used:
TypeScript
Compiling the above code produces the following JavaScript code:
JavaScript
The output is:
Call function
Function Overloading
Overloading means methods have the same name but different parameters, and the return types can be the same or different.
Each overloaded method (or constructor) must have a unique parameter type list.
Different parameter types:
function disp(string):void; function disp(number):void;
Different number of parameters:
function disp(n1:number):void; function disp(x:number,y:number):void;
Different order of parameter types:
function disp(n1:number,s1:string):void; function disp(s:string,n:number):void;
If the parameter types are different, the parameter type should be set toany。
If the number of parameters differs, you can set the different parameters as optional.
Example
The following example defines different parameter types and different numbers of parameters:
TypeScript
Compiling the above code produces the following JavaScript code:
JavaScript
The output is:
abc undefined 1 xyzOther extensions