官术网_书友最值得收藏!

  • Expert Angular
  • Mathieu Nayrolles Rajesh Gunasundaram Sridhar Rao
  • 232字
  • 2021-07-15 17:05:33

Optional and default parameters

Say, for example, we have a function with three parameters, and sometimes we may only pass values for the first two parameters in the function. In TypeScript, we can handle such scenarios using the optional parameter. We can define the first two parameters as normal and the third parameter as optional, as given in the following code snippet:

function CustomerName(firstName: string, lastName: string, middleName?: string) { 
    if (middleName) 
        return firstName + " " + middleName + " " + lastName; 
    else 
        return firstName + " " + lastName; 
} 
//ignored optional parameter middleName 
var customer1 = customerName("Rajesh", "Gunasundaram"); 
//error, supplied too many parameters 
var customer2 = customerName("Scott", "Tiger", "Lion", "King");  
//supplied values for all 
var customer3 = customerName("Scott", "Tiger", "Lion");  

Here, middleName is the optional parameter, and it can be ignored when calling the function.

Now, let's see how to set default parameters in a function. If a value is not supplied to a parameter in the function, we can define it to take the default value that is configured:

function CustomerName(firstName: string, lastName: string, middleName: 
string = 'No Middle Name') { if (middleName) return firstName + " " + middleName + " " + lastName; else return firstName + " " + lastName; }

Here, middleName is the default parameter that will have No Middle Name by default if the value is not supplied by the caller.

主站蜘蛛池模板: 祁门县| 邢台县| 崇信县| 凤城市| 郴州市| 马鞍山市| 张家界市| 鄱阳县| 运城市| 泾阳县| 安福县| 长子县| 华蓥市| 乌兰浩特市| 南投县| 蒲江县| 江源县| 靖远县| 金沙县| 张家界市| 银川市| 防城港市| 句容市| 麻江县| 包头市| 察隅县| 高尔夫| 溧阳市| 莱州市| 中江县| 左贡县| 玉屏| 阜宁县| 海晏县| 怀安县| 宝坻区| 叶城县| 富平县| 浪卡子县| 平凉市| 华蓥市|