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

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.

主站蜘蛛池模板: 徐闻县| 会宁县| 外汇| 通江县| 广丰县| 项城市| 襄汾县| 龙里县| 栾川县| 碌曲县| 尉氏县| 永修县| 镇原县| 兴山县| 昌平区| 门头沟区| 乐至县| 永靖县| 蕲春县| 隆林| 平塘县| 石景山区| 文登市| 阿克陶县| 临漳县| 浙江省| 湛江市| 普宁市| 西昌市| 碌曲县| 子长县| 军事| 连山| 广平县| 桦南县| 宁武县| 故城县| 定州市| 洪雅县| 靖州| 年辖:市辖区|