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

Open-ended tuples

Before TypeScript 3, tuples had to have a fixed amount of elements. TypeScript 3 gives us a little more flexibility with rest elements. rest elements are similar to rest parameters, described in the last section, but they work with tuple element types. A rest element allows us to define an open-ended tuple.

Time to go through an example:

  1. In the TypeScript playground, let's create a tuple with the first element being a string and subsequent elements being numbers:
type Scores = [string, ...number[]];
  1. We should be able to use this structure to store someone's name with an infinite amount of scores. Let's give this a go for Billy and three scores:
const billyScores: Scores = ["Billy", 60, 70, 75];
  1. Let's move on to try Sally and four scores:
const sallyScores: Scores = ["Sally", 60, 70, 75, 70];

Both these variables compile fine, as we would expect, because we have defined the numbers as open-ended.

主站蜘蛛池模板: 库车县| 新兴县| 嵊泗县| 昭苏县| 平武县| 丰顺县| 泸溪县| 富阳市| 宝山区| 苏尼特右旗| 靖宇县| 静宁县| 临湘市| 达拉特旗| 库尔勒市| 金堂县| 固阳县| 于田县| 黄龙县| 石城县| 庆阳市| 西乌| 稷山县| 湘潭市| 咸阳市| 谢通门县| 彩票| 东乌珠穆沁旗| 福鼎市| 宁阳县| 兴安县| 亚东县| 若尔盖县| 仙居县| 辽源市| 台东县| 平武县| 兴业县| 冷水江市| 齐河县| 灌南县|