You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
let myAdd: (x: number,y: number)=>number=function(x: number,y: number): number{returnx+y;};
只要参数类型是匹配的,那么就认为它是有效的函数类型,而不在乎参数名是否正确。
可选参数
在参数名旁使用 ?实现可选参数的功能
functionbuildName(firstName: string,lastName?: string){if(lastName)returnfirstName+" "+lastName;elsereturnfirstName;}letresult1=buildName("Bob");// works correctly nowletresult2=buildName("Bob","Adams","Sr.");// error, too many parametersletresult3=buildName("Bob","Adams");// ah, just right
functionbuildName(firstName: string,lastName="Smith"){returnfirstName+" "+lastName;}letresult1=buildName("Bob");// works correctly now, returns "Bob Smith"letresult2=buildName("Bob",undefined);// still works, also returns "Bob Smith"letresult3=buildName("Bob","Adams","Sr.");// error, too many parametersletresult4=buildName("Bob","Adams");// ah, just right
letsuits=["hearts","spades","clubs","diamonds"];functionpickCard(x: {suit: string;card: number;}[]): number;functionpickCard(x: number): {suit: string; card: number;};functionpickCard(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(typeofx=="object"){letpickedCard=Math.floor(Math.random()*x.length);returnpickedCard;}// Otherwise just let them pick the cardelseif(typeofx=="number"){letpickedSuit=Math.floor(x/13);return{suit: suits[pickedSuit],card: x%13};}}letmyDeck=[{suit: "diamonds",card: 2},{suit: "spades",card: 10},{suit: "hearts",card: 4}];letpickedCard1=myDeck[pickCard(myDeck)];alert("card: "+pickedCard1.card+" of "+pickedCard1.suit);letpickedCard2=pickCard(15);alert("card: "+pickedCard2.card+" of "+pickedCard2.suit);
函数
在参数名旁使用 ?实现可选参数的功能
在TypeScript里,我们也可以为参数提供一个默认值当用户没有传递这个参数或传递的值是undefined时。 它们叫做有默认初始化值的参数
参考链接
函数 ts中文网
The text was updated successfully, but these errors were encountered: