可选参数
函数可选参数 加?,只能写在必填参数的后面
function buildName(firstName: string, lastName?: string): string {return firstName + lastName;}
默认参数
function buildName(firstName: string, lastName: string = '翠花'): string {return firstName + lastName;}
编译后:
function buildName(firstName, lastName) {if (lastName === void 0) {lastName = '翠花';}return firstName + lastName;}
剩余参数
// 剩余参数:编译后其实是用了argumentsfunction buildName3(firstName: string, ...resOfName: string[]): string {let name = '';resOfName.forEach((item) => {name += item;});return firstName + name;}console.log(buildName3('1', '2', '多少都可以'));
编译后其实是用了 arguments
// 编译后:function buildName3(firstName) {var resOfName = [];for (var _i = 1; _i < arguments.length; _i++) {resOfName[_i - 1] = arguments[_i];}var name = '';resOfName.forEach(function (item) {name += item;});return firstName + name;}console.log(buildName3('1', '2', '多少都可以'));
this
this :函数被调用的上下文,箭头函数的 this 指向声明位置的上下文
interface Card {suit: string;card: number;}interface Deck {suits: string[];cards: number[];// 指定this类型,如果哪里有写错this的引用,会智能提示createCardPicker(this: Deck): () => Card;}let deck: Deck = {suits: ['黑桃', '红桃', '梅花', '尖尖'],cards: Array(52),createCardPicker: function () {// 箭头函数,this指向函数声明时的thisreturn () => {let pickedCard = Math.floor(Math.random() * 52);let pickedSuit = Math.floor(pickedCard / 13);return {suit: this.suits[pickedSuit],card: pickedCard % 13,};};},};
重载
函数的参数类型、个数不同,匹配对应的签名
function run(x: number): number;function run(x: string, y: string): string;function run(x: number | string, y?: string) {if (typeof x === 'number') {return x;} else if (typeof y === 'string') {return y;}}
