- 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.
- Python自動化運維快速入門
- JavaFX Essentials
- C語言程序設計教程(第2版)
- PLC編程及應用實戰
- Reactive Programming With Java 9
- SQL Server 2012數據庫管理與開發項目教程
- Java 11 Cookbook
- 表哥的Access入門:以Excel視角快速學習數據庫開發(第2版)
- PHP編程基礎與實例教程
- 詳解MATLAB圖形繪制技術
- Go語言底層原理剖析
- 深度探索Go語言:對象模型與runtime的原理特性及應用
- Java Web開發教程:基于Struts2+Hibernate+Spring
- 3D Printing Designs:Design an SD Card Holder
- Learning HTML5 by Creating Fun Games