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

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.

主站蜘蛛池模板: 太原市| 田东县| 栾川县| 五家渠市| 郑州市| 息烽县| 洛扎县| 阿合奇县| 阳高县| 同德县| 阿克陶县| 金平| 仁布县| 宜章县| 南陵县| 绥滨县| 吐鲁番市| 东山县| 文水县| 达日县| 黄冈市| 区。| 昂仁县| 莲花县| 德令哈市| 望江县| 改则县| 临泉县| 开阳县| 沽源县| 马鞍山市| 荔浦县| 连平县| 礼泉县| 北辰区| 长丰县| 通许县| 义马市| 高州市| 渝北区| 班戈县|