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

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.

主站蜘蛛池模板: 腾冲县| 大港区| 白银市| 三明市| 镇赉县| 澎湖县| 景宁| 同德县| 温州市| 封丘县| 永靖县| 甘南县| 舒城县| 叙永县| 吕梁市| 双辽市| 色达县| 慈溪市| 铅山县| 南京市| 鄂尔多斯市| 游戏| 民县| 宜良县| 樟树市| 萨嘎县| 翁牛特旗| 银川市| 延长县| 龙口市| 普格县| 四子王旗| 郎溪县| 三台县| 牟定县| 车致| 灯塔市| 富顺县| 青神县| 太白县| 泊头市|