Typescript Study Notes (iv): functions

Source: Internet
Author: User
Tags types of functions

In this note, let's take a look at the functions in typescript.

function type

There are two ways to define a function in JavaScript, such as the following:

1 // named Functions 2 function Add (x, y) {3     return x+y; 4 }56// anonymous functions 7var function return x+y; };

The corresponding wording in typescript is as follows:

1 function Add (X:number, Y:number): number {2     return x+y; 3 }45varfunctionreturn x+y; };

And typescript in the type of function can also be defined, such as our above Myadd does not define the type, you can assign any type of function to it, of course, something other than the assignment function can also, this is certainly not a good practice, we look at the following another way of writing:

var myadd: (Basevalue:number, increment:number) =>number =     functionreturn x+y;};

Here we define myadd to be a function, and must be a function with a return value of two number parameter, and other types of functions assigned to Myadd will give an error.

Defining function types

See here you are not Huanran Dawu, this is not the delegation of C #?

It would be troublesome to use the above notation in places where the function type is used, so you can define a function type that is directly defined as the type of the function where you want to use it, as follows:

1 /**2 * This can be seen as a delegate in C #.3  */4 Interface Iprogresshandler5 {6     /**7 * Progress reporting method.8 * @param progress progress.9 * @returns {} none.Ten      */ One(Progress:number):void; A } -  - class Loading the { - private _progresshandler:iprogresshandler; -  - Load (url:string, Callback:iprogresshandler) +     { -          This. _progresshandler =callback; +         //Load Complete A          This. _progresshandler (1.0); at     } - } -  - functionRun () - { -     varLoad:loading =NewLoading (); inLoad. Load ("http://xxx/",function(P:number):void -     { toAlert ("Load:" +p); +     }); - } the  *Run ();
Optional and default parameters

Optional parameters, indicating that the parameter can be filled or not filled in, use?: is indicated as follows:

1 functionBuildname (firstname:string, lastName?): String)2 {3     if(LastName)4         returnFirstName + "" +LastName;5     Else6         returnFirstName;7 }8 9Alert (Buildname ("LiLie"));TenAlert (Buildname ("Meimei", "Han"));

If no arguments are provided, the LastName is undefined.

The default parameter indicates that the parameter is not filled by using the provided default value, as follows:

1 function buildname (firstname:string, lastname:string = "Wang")2{3     return firstName + "" + LastName; 4 }56 alert (buildname ("LiLie")); // LiLie Wang 7 alert (Buildname ("Meimei", "Han")); // Meimei Han
Object parameter Type

Let's look at the following wording:

function Getarea (quad:object) {    return quad["width"] * quad["height"];} Alert (Getarea ({width:ten, height:20}));

There is a problem with this writing, if the incoming argument does not have a width or height when the runtime will be error-free, but compile without error, then how can you make a type judgment at compile time?

In general, other languages use interfaces to solve this problem, but Typescript has a faster way to do this, as follows:

1 function Getarea (Quad:{width:number, height:number}) 2 {3     return quad.width * quad.height; 4 }56 alert (Getarea ({width:10, height:20}));

Optional parameters are also supported, but default parameters are not supported, as follows:

1 functionGetarea (quad:{width:number, height?): number})2 {3     if(Quad.height = =undefined)4     {5Quad.height = 10;6     }7     returnQuad.width *Quad.height;8 }9 TenAlert (Getarea ({width:10}));
Variable parameters

A variable parameter indicates that any parameter can be filled in arbitrarily, as follows:

1 function buildname (firstname:string, ... restofname:string[]) 2 {3    alert (restofname.length); 4     return firstName + "," + Restofname.join (","); 5 }67 alert (Buildname ("LiLie")); 8 alert (buildname ("LiLie", "Meimeihan")); 9 alert (buildname ("LiLie", "Meimeihan", "Lintao", "Laowang"));
Lambda

Shorthand for anonymous functions, we have come to the door example to see:

1 /**2 * This can be seen as a delegate in C #.3  */4 Interface Iprogresshandler5 {6     /**7 * Progress reporting method.8 * @param progress progress.9 * @returns {} none.Ten      */ One (Progress:number): string; A } -  - class Loading the { - private _progresshandler:iprogresshandler; -  - Load (url:string, Callback:iprogresshandler) +     { -          This. _progresshandler =callback; +         //Load Complete AAlert This. _progresshandler (1.0)); at     } - } -  - functionRun () - { -     varLoad:loading =NewLoading (); inLoad. Load ("http://xxx/", p = = { -Alert ("Load:" +p); to         return"Hello lambda!"; +     }); - } the  *Run ();

Typescript Lambda usage is consistent with C #.

Lambda and this

Let's take a look at this example:

1 var messenger = {2     message: "Hello World",3     function () {4         setTimeout (() = {alert (this. message) ; 5     }6}; 7 Messenger.start ();

The compiled JS is as follows:

1 varMessenger = {2Message: "Hello World",3Startfunction () {4         var_this = This;5SetTimeout (function () {6 alert (_this.message);7}, 3000);8     }9 };TenMessenger.start ();

More information can be viewed: http://www.codebelt.com/typescript/arrow-function-typescript-tutorial/

Overload

Typescript functions support overloading, and functions with the same name can perform different logic depending on the type and number of arguments, but defining overloaded functions is slightly different from other languages: in typescript, you need to write a function declaration of the same name, and then write the implementation in a function of the same name. And you need to determine the parameter type (compare chicken ribs):

1 functionattr (name:string): string;2 functionattr (name:string, value:string): Accessor;3 functionattr (map:any): Accessor;4 5 functionattr (Nameormap:any, value?): String): any {6     if(Nameormap &&typeofNameormap = = = "Object") {7         //Handle Map case8     }9     Else {Ten         //Handle String case One     } A}

Typescript Study Notes (iv): functions

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.