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

Tuple function parameters

Tuple function parameters in TypeScript 3 allow us to create strongly-typed rest parameters.

Time for an example:

  1. When we first looked at rest parameters, we created a pure JavaScript version of logScores that collected an unlimited amount of arguments in a scores variable:
function logScores(...scores) {
console.log(scores);
}
  1. In TypeScript 3, we can now make this example strongly-typed with a tuple rest parameter. Let's give this a try in the TypeScript playground:
function logScores(...scores: [...number[]]) {
console.log(scores);
}
  1. Let's call our function with some scores:
logScores(50, 85, 75);

We don't get a compiler error, and if we run the program, we get an array containing 50, 85, 75 output in the console.

We can create an enhanced version of our function that uses the Scores type from the Open-ended tuples section.

  1. The function will take in the name, as well as an unlimited set of scores:
type Scores = [string, ...number[]];

function logNameAndScores(...scores: Scores) {
console.log(scores);
}
  1. Let's try to call our function with some scores from Sally:
logNameAndScores("Sally", 60, 70, 75, 70);

If we run the program, Sally and her array of scores will be output to the console.

主站蜘蛛池模板: 江源县| 克什克腾旗| 五大连池市| 卢龙县| 唐海县| 五家渠市| 东安县| 通化县| 玉田县| 临邑县| 通辽市| 民丰县| 大渡口区| 富阳市| 宜良县| 开原市| 祁东县| 英吉沙县| 蚌埠市| 乡城县| 定日县| 修文县| 抚顺市| 开封县| 镇远县| 昌吉市| 四子王旗| 文成县| 扎兰屯市| 昌平区| 阜新市| 海城市| 徐州市| 洪江市| 宁德市| 辉县市| 阿克陶县| 增城市| 长沙县| 聊城市| 江城|