官术网_书友最值得收藏!

Coping with a variable number of parameters using REST

The final thing we need to look at with regard to REST is the idea of functions having REST parameters. These aren't the same as REST properties but the syntax is so similar that we should find it easy to pick up. The problem that REST parameters solves is to cope with a variable number of parameters being passed into a function. The way to identify a REST parameter in a function is that it is preceded by the ellipsis and that it is typed as an array.

In this example, we are going to log out a header followed by a variable number of instruments:

function PrintInstruments(log : string, ...instruments : string[]) : void {
console.log(log);
instruments.forEach(instrument => {
console.log(instrument);
});
}
PrintInstruments('Music Shop Inventory', 'Guitar', 'Drums', 'Clarinet', 'Clavinova');

As the REST parameter is an array, this gives us access to array functions, which means that we can perform actions such as forEach from it directly. Importantly, REST parameters are different from the arguments object inside a JavaScript function because they start at the values that have not been named in the parameters list, whereas the arguments object contains a list of all of the arguments.

As REST parameters were not available in ES5, TypeScript does the work necessary to provide JavaScript that simulates the REST parameter. First, we will see what this looks like when compiled as ES5, as follows:

function PrintInstruments(log) {
var instruments = [];
// As our rest parameter starts at the 1st position in the list of
// arguments,
// our index starts at 1.
for (var _i = 1; _i < arguments.length; _i++) {
instruments[_i - 1] = arguments[_i];
}
console.log(log);
instruments.forEach(function (instrument) {
console.log(instrument);
});
}

When we look at the JavaScript produced from an ES2015 compilation (you will need to change the entry for target to ES2015 in the  tsconfig.json file), we see that it looks exactly the same as our TypeScript code:

function PrintInstruments(log, ...instruments) {
console.log(log);
instruments.forEach(instrument => {
console.log(instrument);
});
}

At this point, I cannot stress enough how important it is to take a look at the JavaScript that is being produced. TypeScript is very good at hiding complexity from us, but we really should be familiar with what is being produced. I find it a great way to understand what is going on under the covers, where possible, to compile using different versions of the ECMAScript standard and see what code is being produced.

主站蜘蛛池模板: 蓝山县| 南靖县| 宝丰县| 团风县| 迁西县| 修武县| 舒兰市| 耒阳市| 丰县| 兰溪市| 缙云县| 安国市| 安阳市| 博客| 深圳市| 江西省| 安远县| 花莲市| 舒城县| 依兰县| 阿尔山市| 正宁县| 夏河县| 霞浦县| 宽城| 海安县| 天全县| 兴国县| 墨脱县| 德清县| 南开区| 定陶县| 固始县| 五河县| 巩义市| 荥阳市| 荣成市| 濮阳市| 平阳县| 枣庄市| 阳山县|