函数可以使用函数之外的变量。理解这个机制如何工作,并能在使用中权衡利弊,对于掌握JS和TS很有帮助。
函数类型
给函数加类型
function add(x: number, y: number): number {
return x + y;
}
是否添加返回值类型,取决于你是否想限制返回值的类型。
函数类型
let myAdd: (x: number, y: number) => number =
function(x: number, y: number): number { return x + y; };
如果没有返回值,返回值类型应该是 void
。
这里的 =>
和箭头函数没有任何关系,只是用于声明函数类型。
可选参数
在ts中,函数定义了几个参数,调用时就传几个参数,不能多也不能少。
function buildName(firstName: string, lastName: string) {
return firstName + " " + lastName;
}
let result1 = buildName("Bob"); // error, too few parameters
let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
let result3 = buildName("Bob", "Adams"); // ah, just right
定义可选参数:
function buildName(firstName: string, lastName?: string) {
if (lastName)
return firstName + " " + lastName;
else
return firstName;
}
let result1 = buildName("Bob"); // works correctly now
let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
let result3 = buildName("Bob", "Adams"); // ah, just right
可选参数必须放在其它参数的后面。
Rest 参数
如果传入的参数个数不确定时,可以这样:
function buildName(firstName: string, ...restOfName: string[]) {
return firstName + " " + restOfName.join(" ");
}
// employeeName will be "Joseph Samuel Lucas MacKinzie"
let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");
Overloads
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 {
// Check to see if we're working with an object/array
// if so, they gave us the deck and we'll pick the card
if (typeof x == "object") {
let pickedCard = Math.floor(Math.random() * x.length);
return pickedCard;
}
// Otherwise just let them pick the 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 }, { 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);
唯一作用就是表示这个函数有多种类型,能增加可读性,并能帮助校验。
作用不大,写法像坨屎。
总结
可以给参数和返回值加类型。
可以定义函数类型。
定义几个参数,必须传几个参数。
可以定义可选参数和 Rest 参数。
网友评论