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

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.

主站蜘蛛池模板: 多伦县| 阜阳市| 新兴县| 乌兰浩特市| 临猗县| 巴东县| 治县。| 阜阳市| 伊川县| 日土县| 虞城县| 达州市| 聂拉木县| 沙雅县| 蒲江县| 五原县| 墨江| 鲁甸县| 鲜城| 杭锦后旗| 贺兰县| 榕江县| 茶陵县| 丰台区| 富平县| 昭通市| 同江市| 贵南县| 登封市| 永和县| 连州市| 深泽县| 沂源县| 区。| 黑山县| 内乡县| 綦江县| 喀喇| 西峡县| 旺苍县| 余姚市|