TypeScript Getting three: TypeScript function type

  • TypeScript function type
  • Function parameters TypeScript
  • this function TypeScript arrow Function
  • TypeScript function overloading

 A, TypeScript function type

 In a previous blog has been declared TypeScript type of variable has made a preliminary resolution, here to review the following:

1  // declare function 
2  function ADD1 (X: Number, Y: Number): Number {
 . 3    return X + Y;
 . 4  }
 . 5  
. 6 the let ADD2 = function (X: Number, Y: Number): Number {
 . 7    return X + Y ;
 8  }
 . 9  
10  // defines the type of function 
. 11 type myAdd = (baseValue: Number, INCREMENT: Number) => Number;
 12 is  // a function of the variable type declaration function 
13 is the let myAdd1: myAdd = function (X: Number, Y: Number): Number {
 14    return X + Y;
 15 }
16 let myAdd2:myAdd = function(x:number,y:number) : number{
17   return x - y;
18 }
19 
20 let hintStamp(str:string):void{
21   console.log(str);
22 }

A function of the type of thing to note, you need to use the type keyword and equal sign "=" assignment type; if you use a colon let declaration and take ":" that is a function of variable declarations, and the function type specified variables this variable as a function of the type not only to its own evaluation of the specified type of function.

 Second, the parameters of the function TypeScript

2.1 as a function of the variable type declaration of the function, the actual parameter name of the function may not be consistent with the type of the parameter name of the function, which is the object of type Object field a little bit different;

1 type myAdd = (baseValue: number, increment: number) => number;
2 let myAdd1:myAdd = function(a:number,b:number) : number{
3   return a + b;
4 }
5 let myAdd2:myAdd = function(x:number,y:number) : number{
6   return x - y;
7 }

2.2 Optional parameters with default parameters:

This non-content is described in detail in the official document, the following brief resolved here, if you do not understand we recommend checking out the official documentation.

Optional parameters means that the parameters of the function when the function is actually called, may not need all incoming correspondence, but when you define a function type, you must set the default parameters.

1  // Example: defining a function type, the parameter b is set to the default parameters: 'typescript' 
2  function foo (A: String, b = 'typescript'): void {
 . 3    the console.log (A + ':' + B);
 . 4  }
 . 5 foo ( 'Hello'); // Hello: typescript

Set the default parameters, you need to set the parameters of the type, TypeScript the IDE will take the initiative for us to infer the type parameter is the type of default values, if the optional parameter to pass values ​​must correspond to the type of default parameters.

In addition to setting the established parameters other than the default, you can also use (parameter name +?) Way to set a non-specific parameter, but the default settings need to set the type of non-specific parameters (parameter name?: Type) default parameters. This optional parameter is not set a specific value, if not to pass the optional parameter value when you call the function will default to undefined.

 1 //这是官方文档中的一个示例:
 2 function buildName(firstName: string, lastName?: string) {
 3   if (lastName){
 4     
 5     return firstName + " " + lastName;
 6   }else{
 7     return firstName;
 8   }   
 9 }
10 
11 let result1 = buildName("Bob");  // works correctly now
12 console.log(result1);
13 let result2 = buildName("Bob", "Adams", "Sr.");  // error, too many parameters
14 let result3 = buildName("Bob", "Adams");  // ah, just right

The remaining parameters 2.3

The remaining parameters on its essence is ES6 collection (res) syntax, use the "..." excess parameters collection, but still need to use arguments when TypeScript converted to ES5 js code to achieve, after all, ES5 version has not collected ( res) syntax. Details can understand ES6 Getting Started: block-level scope (let & const), spread expansion, rest collection

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

Note, however, collected data must be generated by an array syntax, so you must use an array type.

 Three, TypeScript this function and the function of the arrow

About this point in JavaScript has been relatively easy to be a knowledge stun it, do not worry, I've got a blog panacea: JavaScript in this point to rule

Of course, this refers to grammar rules ES6 related changes produced here also: ES6 entry-V: arrow function, function and ES6 new syntax

Of course, it really points to a strict pattern of this problem: JavaScript strict mode

TypeScript this point does not change the rules of JavaScript, but to provide a more friendly warning in the IDE, this function needs through "noImplicitThis" in the tsconfig.json: true open. We know that in JavaScript this point rule is more complex, and TypeScript also made corresponding adjustments in accordance with these rules, where this function on TypeScript point is actually to understand what "noImplicitThis" to our rules tips?

3.1 TypeScript objects will return the function of this warning:

. 1 the let obj = {
 2    STRs: [ "AAA", "BBB", "CCC", "ddd" ],
 . 3    Fun: function () {
 . 4      return  function () { // Here will be prompted to this error because of strict this mode may be undefined, in this type identified TypeScript the IDE to any, it is considered possible undefined situation 
. 5        the let Math.floor index = (Math.random () * this .strs.length);
 . 6        return  this .strs [index];
 . 7      }
 . 8    }
 . 9  }
 10  var Fun = obj.fun ();
 . 11 the console.log (Fun ());

 This problem can be solved using the arrow function:

 1 let obj = {
 2   strs : ["aaa","bbb","ccc","ddd"],
 3   fun:function(){
 4     return () => { //通过箭头函数解决
 5       let index = Math.floor(Math.random() * this.strs.length);
 6       return this.strs[index];
 7     }
 8   }
 9 }
10 var fun = obj.fun();
11 console.log(fun());

3.2 this parameter as a function, not an error message appears, it should be noted that, because the syntax error will occur directly in the native species JavaScritp such an approach. For example example write:

. 1  function F ( the this : void ) { // Here you can give parameter types are not given any TypeScript 
2      // Unfortunately this does not complain 
3 }

There are several reasons, strict mode function is executed only inside this point are undefined, this function is called if the object is bound to an object will call the function. But the key is to be written in the parameter of this would not be TypeScript compiled to native js code, where no error in fact TypeScript this low-level errors to help you automatically handled, so silent this error message.

About this as an argument in TypeScript there is another function, the function is to help maintain this point, such as official this example:

 1 interface Card {
 2     suit: string;
 3     card: number;
 4 }
 5 interface Deck {
 6     suits: string[];
 7     cards: number[];
 8     createCardPicker(this: Deck): () => Card;
 9 }
10 let deck: Deck = {
11     suits: ["hearts", "spades", "clubs", "diamonds"],
12     cards: Array(52),
13     // NOTE: The function now explicitly specifies that its callee must be of type Deck
14     createCardPicker: function(this: Deck) {
15         return () => {
16             let pickedCard = Math.floor(Math.random() * 52);
17             let pickedSuit = Math.floor(pickedCard / 13);
18 
19             return {suit: this.suits[pickedSuit], card: pickedCard % 13};
20         }
21     }
22 }
23 
24 let cardPicker = deck.createCardPicker();
25 let pickedCard = cardPicker();
26 
27 alert("card: " + pickedCard.card + " of " + pickedCard.suit);

createCardPicker above code in line 14: function (this: Deck) {} compiled as such:

1 createCardPicker: function () {
2         var _this = this;
3 }

This above code is the means we used this point to maintain common code when defining interfaces in TypeScript it uses this argument as a way to achieve such a treatment can very clearly see this point to the object itself, and it will also silence this error if this parameter of this method is assigned to another object variable, while other objects may also obtain this method as its own strict parameters TypeScript variable type syntax.

3.3 this point how to maintain this in the callback function? Here is an example of code completion official document:

. 1  interface the UIElement {
 2    addClickListener (the onclick: ( the this : void , E: the Event) => void ): void ;
 . 3  }
 . 4  
. 5  class {Handler
 . 6    info: String;
 . 7    constructor (infoStr: String) {
 . 8      the this .info = infoStr;
 . 9    }
 10    onClickGood = (E: the Event) => { // to this holding function inside the same function by an arrow 
. 11        // CAN Not use here Wallpaper Because this type of IT apos void! 
12 is        the console.log ( this ); //指向Handler的实例对象
13       console.log(this.info);//info
14       console.log('clicked!');
15   }
16 }
17 let h = new Handler('info');
18 class uiElementClass implements UIElement{
19   addClickListener(onclick: (this: void, e: Event) => void): void{
20     onclick(new Event('event'));
21   }
22 }
23 let uiElement:uiElementClass = new uiElementClass();
24 uiElement.addClickListener(h.onClickGood);

 Four, TypeScript function overloading

 About TypeScript function I think for a long time I did not know how to resolve this thing, it sets shining example, I can only copy the code official release here.

 1 let suits = ["hearts", "spades", "clubs", "diamonds"];
 2 
 3 function pickCard(x: {suit: string; card: number; }[]): number;
 4 function pickCard(x: number): {suit: string; card: number; };
 5 function pickCard(x:any): any {
 6     // Check to see if we're working with an object/array
 7     // if so, they gave us the deck and we'll pick the card
 8     if (typeof x == "object") {
 9         let pickedCard = Math.floor(Math.random() * x.length);
10         return pickedCard;
11     }
12     // Otherwise just let them pick the card
13     else if (typeof x == "number") {
14         let pickedSuit = Math.floor(x / 13);
15         return { suit: suits[pickedSuit], card: x % 13 };
16     }
17 }
18 
19 let myDeck = [{ suit: "diamonds", card: 2 }, { suit: "spades", card: 10 }, { suit: "hearts", card: 4 }];
20 let pickedCard1 = myDeck[pickCard(myDeck)];
21 alert("card: " + pickedCard1.card + " of " + pickedCard1.suit);
22 
23 let pickedCard2 = pickCard(15);
24 alert("card: " + pickedCard2.card + " of " + pickedCard2.suit);

Guess you like

Origin www.cnblogs.com/ZheOneAndOnly/p/11780518.html