- 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.
推薦閱讀
- Modular Programming with Python
- Cocos2D-X權威指南(第2版)
- GraphQL學習指南
- 程序設計與實踐(VB.NET)
- 深入淺出Electron:原理、工程與實踐
- BeagleBone Media Center
- React.js Essentials
- Implementing Cisco Networking Solutions
- Python王者歸來
- PostgreSQL Replication(Second Edition)
- HDInsight Essentials(Second Edition)
- 學習OpenCV 4:基于Python的算法實戰
- Learning Python Data Visualization
- JavaScript Concurrency
- Arduino Electronics Blueprints