Blog Park debut, reproduced please indicate the source, thank you for your support. http://www.cnblogs.com/xuema/
Definition and invocation of a function
The syntax for defining a function in Typescript is:
- function function_name(arg:number,arg1:number,....):return_type {
- the code function to execute;
- return data;
- }
Where function is the keyword that declares the function, functionname is the name of the custom function, arg is the argument list, _return_type is the return value type of the function, and code is the one to execute when the function is called. Use the return keyword to return data, which is the data to be returned, enclosed in "{}". The invocation of the function is simple, the following code:
- function Add(x: number, y: number): number { // Define a function that returns a number type
- return x+y;
- }
- Add(5,6); //Call function
Of course, there can be no return value.
anonymous functions
An anonymous function is a function that has no name but a principal and does not require a return type, and its return value type is inferred from the return statement within the body of the function. The following code:
- var myadd = function(x:number, y:number) { //define anonymous functions
- return x+y;
- };
- Myadd(3,4); //Call anonymous function
Optional and default parameters
Optional parameter: After the parameter name, a question mark is added before the colon, indicating that the parameter is optional. The following code:
- function buildname(firstName: string, lastName?: string ) { //lastname is an optional parameter
- if (lastName)
- return firstName + "" + lastName;
- Else
- return firstName;
- }
- var result1 = buildname("Bob"); //Call Bob correctly
- var result2 = buildname("Bob", "Adams"); //Call Bob Adams correctly
Default parameter: Given a value directly after the parameter name, if the value is not passed in, it will be assigned to the default value. The following code:
- function buildname(firstName: string, lastName = "Smith") {
- return firstName + "" + lastName;
- }
- var result1 = buildname("Bob"); //Does not pass in the second parameter, it is assigned the default Smith, and the result is: Bob Smith
- var result2 = buildname("Bob", "Adams"); //Result: Bob Adams
Note: Optional parameters and default parameters must be at the end of the parameter list.
Free interactive exercises and more introductory learning content here (Hui Zhi network): http://www.hu bwiz.com/class/55b724ab3ad79a1b05dcc26c Remove the space in the middle of the domain name
Definition and invocation of a function