Wednesday, August 1, 2018

Rest Parameters in TypeScript

In TypeScript, Rest Parameters are often used in functions to specify the parameters when the number of parameters is unknown.

Let’s go by a sample scenario. Imagine we need to have a method which will return us the full address (nicely separated by “,”) when different parts of the address are supplied. Some addresses have Address Line 1, Address Line 2 etc., and for some, there is no Address Line 2, likewise.

In this case, there is no fixed number of parameters. To cater such a requirement, we can have the following function with Rest Parameters.
function buildAddress(...addressLines) {
    return addressLines.join(", ");
};
Here the Rest Parameter is the addressLines, we are using JavaScript split operator (ellipsis) to specify that.

With TypeScript it’s always better to be explicit. You can specify the type of the Rest Parameters as well. And note, it should always be an array type as behind the scene it really is an array.
function buildAddress(...addressLines: string[]) {
    return addressLines.join(", ");
};
We can call the function like below.
console.log(buildAddress("111-2222", "Bing Street", "Springfield Gardens", "NY", "33333"));
// 111-2222, Bing Street, Springfield Gardens, NY, 33333

console.log(buildAddress("111-2222", "Springfield Gardens", "NY", "33333"));
// 111-2222, Springfield Gardens, NY, 33333
And you can even not pass anything at all.
console.log(buildAddress());
Isn’t it nice!

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment