REST Parameters in TypeScript
In this article, we will take a look at Rest Parameters. Rest parameters are useful when the number of input variables in a function are unknown. When we are using rest parameters, we need to declare the type of variable and rest parameters that will package all of the arguments that are passed in.
In the following example, we have a class "Products". We have one single function which accepts a string "productType" and a rest parameter "models". We are not sure about the number of models to be passed during runtime. So, we define "models" as rest parameter which is an array of string and will take all the arguments.
To make a parameter a "Rest" parameter, we have to specify "..." three dots before the rest parameters name, which is known as ellipsis. In the below given example, we create an instance of class "Products" and call the "printProductNames()" function which simply loops over the rest "models" parameter and logs the name in the browser's console.
class Products { public printProductNames(...products: string[]): void { for (let product of products) { console.log(product); } } } let iPhone: Products = new Products(); console.log("Listing all iPhones: "); iPhone.printProductNames("iPhone 4", "iPhone 4S", "iPhone 5", "iPhone 5S", "iPhone 6", "iPhone 6S");
In this example the function accepts 2 parameters where the first one specify's the type and all others will be the phone models. Please note that Rest parameter always has to be the last parameter in a function. We can pass in any number of arguments to rest parameter. If we do not pass in any arguments in rest parameters, then the program will throw error and highlight rest parameter as undefined. In order to make sure our rest parameter accept strings, we need to define restDetails as string ...models:string[]) . Regardless of the data type that defines the rest parameter, it will always store as an array. Finally we make use of ES6's template string syntax to concatenate the product type and the model and finally log the output.
Thus we can conclude that, in order to pass in multiple values as an input argument we make use of Rest parameters. To demonstrate the usage of Rest parameters we passed in string values. But you can even pass complex objects or any other type as per your business requirements