TypeScript Functions
A function is a group of statements that perform a task together.
You can divide code into different functions. How to divide code into different functions is up to you, but logically, the 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. A function definition provides the actual body of the function.
Function definition
A function is a code block wrapped in curly braces, preceded by the keyword function:
The syntax format is as follows:
function function_name()
{
// Execute code
}
Example
TypeScript
function
(
)
{
//
Function definition
console
.
log
(
"
Calling a function
"
)
}
Calling a function
The code inside a function is executed only when the function is called.
The syntax format is as follows:
function_name()
Example
TypeScript
function
test
(
)
{
//
Function definition
console
.
log
(
"
Calling a function
"
)
}
test
(
)
//
Calling a function
Function return value
Sometimes we want a function to return its execution result 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 format 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 return value must be consistent with the function's defined return type (return_type).
Example
TypeScript
//
Function definition
function
greet
(
)
:
string
{
//
Return a string
return
"
Hello World
"
}
function
caller
(
)
{
var
msg
=
greet
(
)
//
Call the greet() function
console
.
log
(
msg
)
}
//
Calling a function
caller
(
)
-
The example defines a function greet()whose return value is of type string.
-
greet() The function returns via the return statement to the calling place, namely the variable msg, and then outputs the returned value..
Compile the above code to get the following JavaScript code:
JavaScript
//
Function definition
function
greet
(
)
{
return
"
Hello World
"
;
}
function
caller
(
)
{
var
msg
=
greet
(
)
;
//
Call the greet() function
console
.
log
(
msg
)
;
}
//
Calling a function
caller
(
)
;
Functions with parameters
When calling a function, you can pass values to it; these values are called parameters.
These parameters can be used inside the function.
You can send multiple parameters to a function, separated by commas:
The syntax format is as follows:
function func_name( param1 [:datatype], param2 [:datatype]) {
}
-
param1 and param2 are parameter names.
-
datatype is the parameter type.
Example
TypeScript
function
add
(
x
:
number
,
y
:
number
)
:
number
{
return
x
y
;
}
console
.
log
(
add
(
1
,
2
)
)
-
The example defines a function add(), and the return value is of type number.
-
add() The function defines two parameters of type number, adds them together, and returns the result.
Compile the above code to get the following JavaScript code:
JavaScript
function
add
(
x
,
y
)
{
return
x
y
;
}
console
.
log
(
add
(
1
,
2
)
)
;
The output is:
3
Optional parameters and default parameters
Optional arguments
In TypeScript functions, if we define parameters, we must pass them, unless we mark them as optional; optional parameters are marked with a question mark ?.
Example
TypeScript
function
buildName
(
firstName
:
string
,
lastName
:
string
)
{
return
firstName
"
"
lastName
;
}
let
result1
=
buildName
(
"
Bob
"
)
;
//
Error: missing parameter
let
result2
=
buildName
(
"
Bob
"
,
"
Adams
"
,
"
Sr.
"
)
;
//
Error: too many parameters
let
result3
=
buildName
(
"
Bob
"
,
"
Adams
"
)
;
//
Correct
In the following example, we set lastName as an optional parameter:
TypeScript
function
buildName
(
firstName
:
string
,
lastName
?:
string
)
{
if
(
lastName
)
return
firstName
"
"
lastName
;
else
return
firstName
;
}
let
result1
=
buildName
(
"
Bob
"
)
;
//
Correct
let
result2
=
buildName
(
"
Bob
"
,
"
Adams
"
,
"
Sr.
"
)
;
//
Error: too many parameters
let
result3
=
buildName
(
"
Bob
"
,
"
Adams
"
)
;
//
Correct
Optional parameters must follow required parameters. If in the above example we wanted firstName to be optional and lastName required, we would need to adjust their order, placing firstName later.
It's fine if all of them are optional.
Default arguments
We can also set default values for parameters, so that when calling the function, if no value is passed for a parameter, the default 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 at the same time.
Example
In the following example, the function's rate parameter has a default value of 0.50; if no argument is passed when calling the function, 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 are cases where we don't know how many arguments to pass to a function; in such cases we can use rest parameters.
Rest parameter syntax allows us to pass an indefinite number of arguments as an array.
TypeScript
The last named parameter of a function, restOfName, is prefixed with ...; it becomes an array of the remaining arguments, with indices 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 declared dynamically at program runtime; apart from having no 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 format 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
A self-invoking anonymous function is invoked by adding () after the function:TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output is:
Hello!!
constructor
TypeScript also supports defining functions using JavaScript's built-in Function() constructor:
The syntax format is as follows:
var res = new Function ([arg1[, arg2[, ...argN]],] functionBody)
Parameter Description:
- arg1, arg2, ... argN: parameter list.
- functionBody: a string containing JavaScript statements including the function definition.
Example
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output is:
12
Recursive function
A recursive function is one that calls itself within the function.For example:
Once upon a time there was a mountain, and in the mountain there was a temple, and in the temple there was an old monk who was telling a story to a little monk! What was the story? "Once upon a time there was a mountain, and in the mountain there was a temple, and in the temple there was an old monk who was telling a story to a little monk! What was the story? 'Once upon a time there was a mountain, and in the mountain there was a temple, and in the temple there was an old monk who was 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.
The syntax of an arrow function expression is shorter than that of a function expression.
The function has 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
The 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
Compile the above code to get the following JavaScript code:
JavaScript
The output is:
110We can omit specifying parameter types and let the function infer them from its body:
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output is:
12 是一个数字 Tom 是一个字符串
Single parameter () is optional:
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output is:
输出为 12
When there are no parameters, you can use empty parentheses:
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output is:
调用函数
function overloading
Overloading means methods have the same name but different parameters; return types may 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 parameter types differ, the parameter types should be set to any。
If the number of parameters differs, you can set the different parameters as optional.
Example
The following example defines differences in parameter types and parameter count:
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output is:
abc undefined 1 xyz