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

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.

主站蜘蛛池模板: 娱乐| 兴安盟| 如皋市| 大渡口区| 建宁县| 平顺县| 邢台市| 固原市| 彭山县| 德清县| 和林格尔县| 柏乡县| 枣庄市| 交城县| 晋宁县| 青田县| 潜江市| 高雄市| 长泰县| 林周县| 秀山| 恩平市| 嘉义县| 繁峙县| 鱼台县| 许昌市| 东宁县| 双城市| 九台市| 普兰店市| 长宁区| 宁蒗| 车险| 三明市| 鄂伦春自治旗| 临安市| 张家港市| 河间市| 潞城市| 蒲城县| 蓬安县|