Rest parameters

One of the big advantages of the flexibility of JavaScript when defining functions is the functionality to accept an unlimited non-declared array of parameters in the form of the arguments object. In a statically typed context such as TypeScript, this might not be possible, but it actually is by means of the REST parameter's object. Here, we can define, at the end of the arguments list, an additional parameter prefixed by ellipsis (...) and typed as an array:

function greetPeople(greeting: string, ...names: string[]): string{
return greeting + ', ' + names.join(' and ') + '!';
}

alert(greetPeople('Hello', 'John', 'Ann', 'Fred'));

It's important to note that the Rest parameters must be put at the end of the arguments list and can be left out whenever not required. Let's have a look at the resulting ES5 code to understand what the TypeScript compiler produces:

function greetPeople(greeting) {
var names = [];
for (var _i = 1; _i < arguments.length; _i++) {
names[_i - 1] = arguments[_i];
}
return greeting + ', ' + names.join(' and ') + '!';
}

alert(greetPeople('Hello', 'John', 'Ann', 'Fred'));

What we can see here is that the built-in arguments array is being used. Also, that its content is copied over into the names array:

for (var _i = 1; _i < arguments.length; _i++) {
names[_i -1] = arguments[_i];
}

It really makes perfect sense when you think about it. So, Rest parameters is your friend when you don't know the number of arguments.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset