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

function () { //Function Definition console.log("Calling the Function") }

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 test() { //Function Definition console.log("Calling the Function") } test() //Calling the Function

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

//Function Definition function greet():string { //Return a string return "Hello World" } function caller() { var msg = greet() //Call the greet() function console.log(msg) } //Calling the function caller()
  • 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

//Function Definition function greet() { return "Hello World"; } function caller() { var msg = greet(); //Call the greet() function console.log(msg); } //Calling the function caller();

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

function add(x: number, y: number): number { return x + y; } console.log(add(1,2))
  • 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

function add(x, y) { return x + y; } console.log(add(1, 2));

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

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 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

function calculate_discount(price:number,rate:number = 0.50) { var discount = price * rate; console.log("Calculation result:",discount); } calculate_discount(1000) calculate_discount(1000,0.30)

Compile the above code to get the following JavaScript code:

JavaScript

function calculate_discount(price, rate) { if (rate === void 0) { rate = 0.50; } var discount = price * rate; console.log("Calculation result:", discount); } calculate_discount(1000); calculate_discount(1000, 0.30);

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

function buildName(firstName: string, ...restOfName: string[]) { return firstName + " " + restOfName.join(" "); } let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");

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

function addNumbers(...nums:number[]) { var i; var sum:number = 0; for(i = 0;i<nums.length;i++) { sum = sum + nums[i]; } console.log("The sum is:",sum) } addNumbers(1,2,3) addNumbers(10,10,10,10,10)

Compile the above code to get the following JavaScript code:

JavaScript

function addNumbers() { var nums = []; for (var _i = 0; _i < arguments.length; _i++) { nums[_i] = arguments[_i]; } var i; var sum = 0; for (i = 0; i < nums.length; i++) { sum = sum + nums[i]; } console.log("The sum is:", sum); } addNumbers(1, 2, 3); addNumbers(10, 10, 10, 10, 10);

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

var msg = function() { return "hello world"; } console.log(msg())

Compile the above code to get the following JavaScript code:

JavaScript

var msg = function () { return "hello world"; }; console.log(msg());

The output is:

hello world

Anonymous function with parameters:

TypeScript

var res = function(a:number,b:number) { return a*b; }; console.log(res(12,2))

Compile the above code to get the following JavaScript code:

JavaScript

var res = function (a, b) { return a * b; }; console.log(res(12, 2));

The output is:

24

Self-invoking Anonymous Functions

An anonymous function can be self-invoked by using () after the function:

TypeScript

(function () { var x = "Hello!!"; console.log(x) })()

Compile the above code to get the following JavaScript code:

JavaScript

(function () { var x = "Hello!!"; console.log(x) })()

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

var myFunction = new Function("a", "b", "return a * b"); var x = myFunction(4, 3); console.log(x);

Compile the above code to get the following JavaScript code:

JavaScript

var myFunction = new Function("a", "b", "return a * b"); var x = myFunction(4, 3); console.log(x);

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

function factorial(number) { if (number <= 0) { //Stop execution return 1; } else { return (number * factorial(number - 1)); //Call itself } }; console.log(factorial(6)); //Output 720

Compile the above code to get the following JavaScript code:

JavaScript

function factorial(number) { if (number <= 0) { //Stop execution return 1; } else { return (number * factorial(number - 1)); //Call itself } } ; console.log(factorial(6)); //Output 720

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

var foo = (x:number)=>10 + x console.log(foo(100)) //The output is 110

Compile the above code to get the following JavaScript code:

JavaScript

var foo = function (x) { return 10 + x; }; console.log(foo(100)); //The output is 110

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

var foo = (x:number)=> { x = 10 + x console.log(x) } foo(100)

Compiling the above code produces the following JavaScript code:

JavaScript

var foo = function (x) { x = 10 + x; console.log(x); }; foo(100);

The output is:

110
We don't need to specify the parameter types; the types are inferred within the function:

TypeScript

var func = (x)=> { if(typeof x=="number") { console.log(x+"is a number") } else if(typeof x=="string") { console.log(x+"is a string") } } func(12) func("Tom")

Compiling the above code produces the following JavaScript code:

JavaScript

var func = function (x) { if (typeof x == "number") { console.log(x + "is a number"); } else if (typeof x == "string") { console.log(x + "is a string"); } }; func(12); func("Tom");

The output is:

12 是一个数字
Tom 是一个字符串

Single parameter()is optional:

TypeScript

var display = x => { console.log("The output is"+x) } display(12)

Compiling the above code produces the following JavaScript code:

JavaScript

var display = function (x) { console.log("The output is" + x); }; display(12);

The output is:

输出为 12

When there are no parameters, empty parentheses can be used:

TypeScript

var disp =()=> { console.log("Function invoked"); } disp();

Compiling the above code produces the following JavaScript code:

JavaScript

var disp = function () { console.log("Calling the function"); }; disp();

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

function disp(s1:string):void; function disp(n1:number,s1:string):void; function disp(x:any,y?:any):void { console.log(x); console.log(y); } disp("abc") disp(1,"xyz");

Compiling the above code produces the following JavaScript code:

JavaScript

function disp(x, y) { console.log(x); console.log(y); } disp("abc"); disp(1, "xyz");

The output is:

abc
undefined
1
xyz
Other extensions