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

Functions with default parameters

When a function has some optional parameters, we must check whether an argument has been passed to the function (just like we did in the previous example) to prevent potential errors.

There are a number of scenarios in which it would be more useful to provide a default value for a parameter when it is not supplied than to make it an optional parameter. Let's rewrite the add function (from the previous section) using the inline if structure:

function add(foo: number, bar: number, foobar?: number): number {
return foo + bar + (foobar !== undefined ? foobar : 0);
}

There is nothing wrong with the preceding function, but we can improve its readability by providing a default value for the foobar parameter instead of using an optional parameter:

function add(foo: number, bar: number, foobar: number = 0): number {
return foo + bar + foobar;
}

To indicate that a function parameter is optional, we need to provide a default value using the = operator when declaring the function's signature. After compiling the preceding examples, the TypeScript compiler will generate an if statement in the JavaScript output to set a default value for the foobar parameter if it is not passed as an argument to the function:

function add(foo, bar, foobar) {
if (foobar === void 0) { foobar = 0; }
return foo + bar + foobar;
}

This is great because the TypeScript compiler generated the code required to prevent potential runtime errors for us.

The void 0 parameter is used by the TypeScript compiler to check whether a variable is equal to undefined. While most developers use the undefined variable to perform this kind of check, most compilers use void 0 because it will always evaluate as undefined. Checking against undefined is less secure because its value could have been modified, as demonstrated by the following code snippet:

function test() {
var undefined = 2; // 2
console.log(undefined === 2); // true
}

Just like optional parameters, default parameters must always be located after any required parameters in the function's parameter list.

主站蜘蛛池模板: 日照市| 西乌珠穆沁旗| 平塘县| 饶河县| 准格尔旗| 新竹县| 隆回县| 城市| 合肥市| 克什克腾旗| 海淀区| 蓝山县| 潼南县| 板桥市| 武乡县| 闸北区| 富民县| 洞头县| 独山县| 南澳县| 元阳县| 山东| 博湖县| 特克斯县| 勃利县| 琼中| 库尔勒市| 榕江县| 白朗县| 乌鲁木齐县| 张北县| 温泉县| 崇信县| 年辖:市辖区| 巴林左旗| 岢岚县| 辛集市| 梁河县| 丰都县| 南汇区| 项城市|