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

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.

主站蜘蛛池模板: 定陶县| 丰都县| 高州市| 长丰县| 容城县| 富源县| 清涧县| 新密市| 甘孜| 黄山市| 满城县| 大邑县| 宁明县| 尉氏县| 江源县| 谢通门县| 江达县| 股票| 拜泉县| 永靖县| 扬州市| 墨玉县| 湖南省| 安阳市| 景泰县| 诸城市| 沁阳市| 古蔺县| 峡江县| 武汉市| 唐河县| 灯塔市| 武乡县| 班玛县| 浠水县| 中阳县| 富民县| 醴陵市| 阿克苏市| 唐河县| 康定县|