函数 可选参数 默认参数 剩余参数
function person(firstName: string, lastName?: string, age: number = 18, ...phone: string[]) { return { firstName, lastName, age, phone: phone }}
this this参数
- 利用箭头函数解决this指向问题
let myObj = {name: 'str',showName: function () { return () => { console.log(this.name); }}}let na = myObj.showName()console.log(na);function f(this: void) {//this不可用}interface Card {suit: stringcard: number}interface Deck {suits: string[]cards: number[]createCardPicker(this: Deck): () => Card}let deck: Deck = {suits: ['1', '2'],cards: Array(10),createCardPicker: function (this: Deck) { return () => { return { suit: this.suits[0], card: this.cards[0] } }}}
重载
let suits = ["hearts", "spades", "clubs", "diamonds"];function pickCard(x): any {// Check to see if we're working with an object/array// if so, they gave us the deck and we'll pick the cardif (typeof x == "object") { let pickedCard = Math.floor(Math.random() * x.length); return pickedCard;}// Otherwise just let them pick the cardelse if (typeof x == "number") { let pickedSuit = Math.floor(x / 13); return { suit: suits[pickedSuit], card: x % 13 };}}let myDeck = [{ suit: "diamonds", card: 2 }, { suit: "spades", card: 10 }, { suit: "hearts", card: 4 }];let pickedCard1 = myDeck[pickCard(myDeck)];alert("card: " + pickedCard1.card + " of " + pickedCard1.suit);let pickedCard2 = pickCard(15);alert("card: " + pickedCard2.card + " of " + pickedCard2.suit);