Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TypeScript Functions

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; 

}

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

(

)

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]) {   

}

Example

TypeScript

function

add

(

x

:

number

,

y

:

number

)

:

number

{

return

x

y

;

}

console

.

log

(

add

(

1

,

2

)

)

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

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

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

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

function addNumbers(...nums:number[]) { var i; var sum:number = 0; for(i = 0;i<nums.length;i++) { sum = sum + nums[i]; } console.log("Sum:",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("Sum:", 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 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

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

A self-invoking anonymous function is invoked by adding () 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!!

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

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

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.

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

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

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

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

Compile the above code to get the following JavaScript code:

JavaScript

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

The output is:

110
We can omit specifying parameter types and let the function infer them from its body:

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

Compile the above code to get 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("Output: "+x) } display(12)

Compile the above code to get the following JavaScript code:

JavaScript

var display = function (x) { console.log("Output: " + x); }; display(12);

The output is:

输出为 12

When there are no parameters, you can use empty parentheses:

TypeScript

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

Compile the above code to get the following JavaScript code:

JavaScript

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

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

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");

Compile the above code to get 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