Typescript Study Notes (iii)-Methods

Source: Internet
Author: User

This article describes how to define and use methods in Typescript.

I. Method standard declaration and use
1 // Method Declaration 2 function func (X:number, Y:number): number {3     return x + y; 4 }

In Typescript, a method declaration can clearly define the type of each parameter, and the type of the return value. At compile time, the compiler checks whether the return value type of the method body conforms to the defined type, and when called, checks whether the passed parameter type conforms to the defined type, and whether the number of arguments conforms to the defined number.

1 Let RESULT1 = Func (1, 2);                     // the correct way to call.  2 Let result2 = Func_lambda (1, 2, 3);           // the wrong way to call. Redundant definition of the number of arguments.  3 Let RESULT3 = Func_lambda (1);                 // the wrong way to call. The number of parameters is less than defined.  4 Let result4 = Func_lambda (' 1 ', ' 2 ');          // the wrong way to call. The parameter type does not conform to the definition. 

In addition, the method declaration supports the use of lambda expressions.

1 // Lambda Expression Declaration 2 function return x + y};

Second, the default parameter declaration

In some cases, the method call only needs to pass in some parameters. Typescript also supports the way the default parameters are declared.

1 //default parameter definition2Let ShowName =function(Firstname:string, LastName?): String): string {3     if(lastName) {4         returnFirstName + "+LastName;5}Else {6         returnFirstName;7     }8 };9 TenLet wholeName1 = ShowName (' star ', ' Lee '); OneLet wholeName2 = ShowName (' stars ');

By appending the parameter name, the parameter is identified by default, and the corresponding parameter position is undefined if the corresponding parameter position is not passed in when called.

Third, default value parameter declaration

In some cases, a method-defined value is used by default when some parameters are not passed in when the methods are called. Typescript also supports the declaration of default value parameters.

1 // default value parameter definition 2 function (firstname:string, lastName = ' Lee '): string {3     return firstName + "+ LastName; 4 }; 5 6 Let WholeName3 = ShowName2 (' stars ');

Identify the parameter with a default value by adding the = sign after the parameter name and assigning a value. Call if the corresponding parameter location does not pass in or pass in undefined, then take the default value, otherwise take the corresponding position of the value passed in.

Four, multi-parameter declaration

Like other strongly typed languages, Typescript supports an unknown number of multiple-parameter passes when defining a method.

1 // multi-parameter definition 2 function (param1:string, ... restparams:string[]): string {3     return param1 + ' + restparams.join ('); 4 }; 5 6 Let Resparamsfuncresult = Restparamsfunc (' A ', ' B ', ' C ');

By adding ... before the name of the entry. (three decimal points), the parameter that identifies the corresponding location can be passed in more than one. Because the parameter type is explicitly defined, the type of multiple arguments passed in must be consistent with the definition, or the compilation will prompt for errors.

V. Other types of parameter declarations

Object type:

// Object Type Parameters function (x: {p1:string}): string {    return= Jsonparamfunc ({p1: ' a '});              // The assignment type is correct let JsonParamFuncResult2 = Jsonparamfunc ({p1: ' A ', P2: ' B '});     // the assignment type is wrong, and the parameter property is more than defined. Let JSONPARAMFUNCRESULT3 = Jsonparamfunc ({p3: ' C '});              // duplicate type error, parameter property name mismatch. 

In the above example, the parameter type is defined as a JSON object that has the property "P1". When a method is called, the passed parameters are strictly in accordance with the definition of the parameter type, the attributes of the parameter object are redundant or less than the definition will prompt the error, and the property name is inconsistent with the definition.

Method type:

 1  //  2  let Funcparamfunc = function  (func: (x:string, y:string) => string): string { 3  Let _x = ' a ' ;  4  let _y = ' B ' ;  5  return   func (_x, _y);  6  };  7  8  let Funparamfuncresult = Funcparamfunc (function  (x, y) {return  x + y}); 

A method parameter type can be defined as a method of a fixed structure, and the method becomes a callback method.

Vi. Method Overloading

Typescript also supports method overloading.

1 //Method Overloading2 functionOverloadfunc (x: {p1:string}): string;3 functionOverloadfunc (X:number): number;4 functionOverloadfunc (x): any {5     if(typeofx = = ' object ') {6         returnX.p1;7     }8 9     if(typeofx = = ' Number ') {Ten         returnx; One     } A } -  -Let OverloadFuncResult1 = Overloadfunc ({p1: ' a ' }); theLet OVERLOADFUNCRESULT2 = Overloadfunc (1);

In the above example, three methods with the same name are declared consecutively:

The first two methods are defined only by methods, and there is no method body. They define the number and representation of overloaded methods.

The parameter of the last method has no type defined, the return value is defined as any, and the method body. It defines the specific implementation of the overloaded method.

Finally, the JavaScript code compiled by the above code is shown and can be compared.

1 //Method Declaration2 functionfunc (x, y) {3     returnX +y;4 }5 varRESULT1 = func (1, 2);//the correct way to call. 6 varRESULT2 = Func_lambda (1, 2, 3);//the wrong way to call. Redundant definition of the number of arguments. 7 varRESULT3 = FUNC_LAMBDA (1);//the wrong way to call. The number of parameters is less than defined. 8 varRESULT4 = Func_lambda (' 1 ', ' 2 ');//the wrong way to call. The parameter type does not conform to the definition. 9 //Lambda Expression DeclarationTen varFunc_lambda =function(x, Y) {returnX +y;}; One //default parameter definition A varShowName =function(FirstName, lastName) { -     if(lastName) { -         returnFirstName + "+LastName; the     } -     Else { -         returnFirstName; -     } + }; - varwholeName1 = ShowName (' star ', ' Lee '); + varwholeName2 = ShowName (' star ')); A //default value parameter definition at varShowName2 =function(FirstName, lastName) { -     if(LastName = = =void0) {lastName = ' Lee '; } -     returnFirstName + "+LastName; - }; - varWholeName3 = ShowName2 (' star ')); - //multi-parameter definition in varRestparamsfunc =function(param1) { -     varRestparams = []; to      for(var_i = 1; _i < Arguments.length; _i++) { +RESTPARAMS[_I-1] =Arguments[_i]; -     } the     returnparam1 + ' + restparams.join ('); * }; $ varResparamsfuncresult = Restparamsfunc (' A ', ' B ', ' C ');Panax Notoginseng //Object Type Parameters - varJsonparamfunc =function(x) { the     returnX.p1; + }; A varJSONPARAMFUNCRESULT1 = Jsonparamfunc ({p1: ' a '});//assignment type is correct the varJSONPARAMFUNCRESULT2 = Jsonparamfunc ({p1: ' A ', P2: ' B '});//the assignment type is wrong, and the parameter property is more than defined.  + varJSONPARAMFUNCRESULT3 = Jsonparamfunc ({p3: ' C '});//duplicate type error, parameter property name mismatch.  - //Method type parameter $ varFuncparamfunc =function(func) { $     var_x = ' a '; -     var_y = ' B '; -     returnfunc (_x, _y); the }; - varFunparamfuncresult = Funcparamfunc (function(x, Y) {returnX +y;});Wuyi functionOverloadfunc (x) { the     if(typeofx = = ' object ') { -         returnX.p1; Wu     } -     if(typeofx = = ' Number ') { About         returnx; $     } - } - varOVERLOADFUNCRESULT1 = Overloadfunc ({p1: ' a ' }); - varOVERLOADFUNCRESULT2 = Overloadfunc (1);

Typescript Study Notes (iii)-Methods

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.