- Learn React with TypeScript 3
- Carl Rippon
- 158字
- 2021-06-10 19:16:42
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:
- 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[]];
- 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];
- 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.
推薦閱讀
- Progressive Web Apps with React
- OpenCV實例精解
- 精通Python自然語言處理
- jQuery開發基礎教程
- Clojure Reactive Programming
- Java Web開發詳解
- Solr Cookbook(Third Edition)
- Building Machine Learning Systems with Python(Second Edition)
- Scratch3.0趣味編程動手玩:比賽訓練營
- Unity&VR游戲美術設計實戰
- 大學計算機基礎
- Oracle實用教程
- 硬件產品設計與開發:從原型到交付
- Node.js區塊鏈開發
- 大學計算機應用基礎(Windows 7+Office 2010)(IC3)