- Hands-On Functional Programming with TypeScript
- Remo H. Jansen
- 342字
- 2021-07-02 14:03:13
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.
- Learn Blockchain Programming with JavaScript
- 簡單高效LATEX
- Visual C++實例精通
- Python高級編程
- Java開發入行真功夫
- Windows Server 2016 Automation with PowerShell Cookbook(Second Edition)
- C#程序設計
- 自然語言處理Python進階
- UVM實戰
- C++從入門到精通(第5版)
- Django 3.0入門與實踐
- 分布式架構原理與實踐
- PowerDesigner 16 從入門到精通
- 零基礎學C++(升級版)
- Mastering ArcGIS Server Development with JavaScript