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

Functions with optional parameters

Unlike JavaScript, the TypeScript compiler will throw an error if we attempt to invoke a function without providing the exact number and types of parameters that its signature declares. Let's look at a code sample to demonstrate it:

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

The preceding function is called add and will take three numbers as parameters, named foo, bar, and foobar. If we attempt to invoke this function without providing exactly three numbers, we will get a compilation error indicating that the supplied parameters do not match the function's signature:

add(); // Error, expected 3 arguments, but got 0.
add(2, 2); // Error, expected 3 arguments, but got 2.
add(2, 2, 2); // OK, returns 6

There are scenarios in which we might want to be able to call the function without providing all of its arguments. TypeScript features optional parameters in functions to help us to increase the flexibility of our functions and overcome such scenarios.

We can indicate to the TypeScript compiler that we want a function's parameter to be optional by appending the character ? to its name. Let's update the previous function to transform the required parameter, foobar, into an optional parameter:

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

Note how we have changed the foobar parameter name into foobar? and are checking the foobar type inside the function to identify whether the parameter was supplied as an argument to the function. After implementing these changes, the TypeScript compiler will allow us to invoke the function without errors when we supply two or three arguments to it:

add(); // Error, expected 2-3 arguments, but got 0.
add(2, 2); // OK, returns 4
add(2, 2, 2); // OK, returns 6

It is important to note that the optional parameters must always be located after the requisite parameters in the function's parameter list.

主站蜘蛛池模板: 丰原市| 疏勒县| 古田县| 门头沟区| 富锦市| 阳原县| 天峻县| 义马市| 普兰店市| 曲周县| 江北区| 黄石市| 房山区| 贵阳市| 丰城市| 密山市| 施甸县| 郧西县| 兴海县| 南康市| 塔城市| 都昌县| 上栗县| 淳安县| 正阳县| 许昌市| 东源县| 蕉岭县| 潼南县| 澄迈县| 山西省| 鄂州市| 江陵县| 安达市| 苗栗市| 惠来县| 日照市| 石泉县| 个旧市| 渑池县| 乡宁县|