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

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.

主站蜘蛛池模板: 靖西县| 福贡县| 哈巴河县| 当阳市| 潼南县| 阳西县| 双鸭山市| 遂平县| 米易县| 平远县| 赣州市| 瑞丽市| 咸丰县| 石楼县| 云梦县| 凤山市| 新营市| 商水县| 延吉市| 景谷| 全南县| 兰考县| 临桂县| 垫江县| 锦屏县| 乌鲁木齐市| 浮梁县| 金塔县| 四子王旗| 宁夏| 高唐县| 罗山县| 冀州市| 中超| 丹江口市| 根河市| 抚松县| 商都县| 区。| 宁安市| 杭锦旗|