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

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:

  1. Let's create the following type alias for an empty tuple:
  type Empty = [];
  1. Let's declare a variable of this type and assign it to an empty array:
  const empty: Empty = [];
  1. 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.

主站蜘蛛池模板: 太和县| 谢通门县| 新乡县| 昭苏县| 望奎县| 南召县| 永新县| 武穴市| 上高县| 湘阴县| 彭阳县| 阿拉善盟| 松原市| 万山特区| 襄垣县| 临桂县| 广东省| 昌平区| 夏河县| 莒南县| 如东县| 天柱县| 盘山县| 瓮安县| 平遥县| 北碚区| 密山市| 岑巩县| 泽州县| 肥城市| 尖扎县| 易门县| 双牌县| 多伦县| 安顺市| 衡水市| 丰台区| 普兰店市| 邵阳县| 萨嘎县| 西吉县|