- Learn React with TypeScript 3
- Carl Rippon
- 209字
- 2021-06-10 19:16:42
Empty tuples
In TypeScript 3, we can now define an empty tuple type. Let's have a little play with this in the TypeScript playground:
- Let's create the following type alias for an empty tuple:
type Empty = [];
- Let's declare a variable of this type and assign it to an empty array:
const empty: Empty = [];
- Now, let's try to declare a variable of this type and assign it to a non-empty array:
const notEmpty: Empty = ["Billy"];
As expected, we get a compilation error:
Why is an empty tuple type useful, though? On its own, it perhaps is not that useful, but it can be used as part of a union type, which we'll cover in detail later in the book. As a quick example for now, we can create a type for no more than three scores, where no scores is also acceptable:
type Scores = [] | [number] | [number, number] | [number, number, number]
const benScores: Scores = [];
const samScores: Scores = [55];
const bobScores: Scores = [95, 75];
const jayneScores: Scores = [65, 50, 70];
const sarahScores: Scores = [95, 50, 75, 75];
All the scores are valid except Sarah's, because four scores aren't allowed in the Scores type.
推薦閱讀
- oreilly精品圖書:軟件開發者路線圖叢書(共8冊)
- R Data Analysis Cookbook(Second Edition)
- 程序設計基礎教程:C語言
- 劍指大數據:企業級數據倉庫項目實戰(在線教育版)
- Vue.js 2 Web Development Projects
- Raspberry Pi Robotic Blueprints
- Lift Application Development Cookbook
- 從0到1:HTML5 Canvas動畫開發
- Struts 2.x權威指南
- 跟戴銘學iOS編程:理順核心知識點
- 視窗軟件設計和開發自動化:可視化D++語言
- MongoDB Administrator’s Guide
- Docker on Windows
- 分布式系統架構與開發:技術原理與面試題解析
- Thymeleaf 3完全手冊