/**typeScript-5 functions * Created by liyanq on 17/6/9. */ //-----------Writing the function type-------// /*A function’s type has the same two parts: the type of the arguments and the return type. When writing out the whole function type, both parts are required*/ //full type type Fun = (x: number, y: number) => number; let myAdd: Fun = function (x: number, y: number): number { return x + y; }; //----------this---------// //this and arrow functions let deck = { suits: ["hearts", "spades", "clubs", "diamonds"], cards: Array(52), createCardPicker: function () { // NOTE: the line below is now an arrow function, allowing us to capture 'this' right here return () => { return () => { let pickedCard = Math.floor(Math.random() * 52); let pickedSuit = Math.floor(pickedCard / 13); return {suit: this.suits[pickedSuit], card: pickedCard % 13}; } } } }; let cardPicker = deck.createCardPicker(); let pickedCard = cardPicker()(); console.log("card of: " + pickedCard.card + " of " + pickedCard.suit); //this parameters /*Node:'this' parameters can not use in arrow functions*/ interface UIElement { addClickListener(onclick: (this: void, e: Event) => void): void; } type fun = (this: void, e: Event) => void; class Handler { info: string; onClickGood(this: void, e: Event) { // can't use this here because it's of type void! console.log('clicked!'); } //不能这样些 // onClickGood2: fun = (this: this, e: Event) => { // this.info = e.type; // }; } let h = new Handler(); let uiElement: UIElement; uiElement.addClickListener(h.onClickGood); //重载 /*注意,"function pickCard(x: any): any"不是重载列表的一部分。 所以它只有2次重载:一个针对的是object,一次针对的是number。 调用"pickCard"并且传入其他类型的参数将会导致错误。*/ let suits = ["hearts", "spades", "clubs", "diamonds"]; function pickCard(x: { suit: string; card: number; }[]): number; function pickCard(x: number): { suit: string; card: number; }; function pickCard(x): any { // 检查我们处理的是什么类型的参数 // 如果是数组对象, 则给定deck并且选择card if (typeof x == "object") { return Math.floor(Math.random() * x.length); } // 否则只选择card else if (typeof x == "number") { let pickedSuit = Math.floor(x / 13); return {suit: suits[pickedSuit], card: x % 13}; } } let myDeck = [ {suit: "diamonds", card: 2, name: "jel"},//这里多写个属性没关系的~~~ {suit: "spades", card: 10}, {suit: "hearts", card: 4}]; let pickedCard1 = myDeck[pickCard(myDeck)]; console.log("card: " + pickedCard1.card + " of " + pickedCard1.suit); let pickedCard2 = pickCard(15); console.log("card: " + pickedCard2.card + " of " + pickedCard2.suit);
[typeScript语法5]functions
最新推荐文章于 2024-01-16 13:14:27 发布