- 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.
推薦閱讀
- Embedded Linux Projects Using Yocto Project Cookbook
- Getting Started with React
- R語言數(shù)據(jù)可視化之美:專業(yè)圖表繪制指南
- 網(wǎng)頁設(shè)計(jì)與制作教程(HTML+CSS+JavaScript)(第2版)
- WebRTC技術(shù)詳解:從0到1構(gòu)建多人視頻會(huì)議系統(tǒng)
- Python語言實(shí)用教程
- 快速入門與進(jìn)階:Creo 4·0全實(shí)例精講
- ScratchJr趣味編程動(dòng)手玩:讓孩子用編程講故事
- C++ Application Development with Code:Blocks
- 零代碼實(shí)戰(zhàn):企業(yè)級(jí)應(yīng)用搭建與案例詳解
- JSP程序設(shè)計(jì)與案例實(shí)戰(zhàn)(慕課版)
- Secret Recipes of the Python Ninja
- 會(huì)當(dāng)凌絕頂:Java開發(fā)修行實(shí)錄
- Raspberry Pi開發(fā)實(shí)戰(zhàn)
- JavaScript高級(jí)程序設(shè)計(jì)(第4版)