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

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.

主站蜘蛛池模板: 宁强县| 上饶县| 青铜峡市| 永修县| 交口县| 嘉义市| 都匀市| 浠水县| 右玉县| 东莞市| 蒙城县| 育儿| 中江县| 武邑县| 蕉岭县| 四会市| 沙湾县| 金坛市| 类乌齐县| 西平县| 华池县| 西平县| 玉门市| 赞皇县| 叶城县| 巴林右旗| 金寨县| 平江县| 台南县| 安达市| 东明县| 徐汇区| 信丰县| 桐城市| 陇南市| 田阳县| 边坝县| 库尔勒市| 千阳县| 会理县| 曲靖市|