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

Optional tuple elements

The final tuple enhancement in TypeScript 3 is the ability to have optional elements. Optional elements are specified using a ? at the end of the element type.

Let's look at another example using our scores theme:

  1. Let's create a type for between one and three scores:
   type Scores = [number, number?, number?];
  1. So, we should be able to create variables to hold between one and three scores:
const samScores: Scores = [55];
const bobScores: Scores = [95, 75];
const jayneScores: Scores = [65, 50, 70];

  As expected, this compiles just fine.

  1. What about four elements? Let's give this a go:
 const sarahScores: Scores = [95, 50, 75, 75];

   We get a compilation error, as we would expect:

  1. If we try no elements, we again get a compilation error:
  const benScores: Scores = [];

When defining optional elements in a tuple, they are restricted to the end of the tuple. Let's try to define a required element after an optional element:

 type ProblematicScores = [number?, number?, number];

 We get a compilation error, as expected:

Optional elements also work in a function rest parameter. Let's try this:

  1. Let's use our scores type in our logScores function we worked with in earlier sections:
type Scores = [number, number?, number?];

function logScores(...scores: Scores) {
console.log(scores);
}
  1. If we try to pass in two scores, the code will compile just fine, because the last parameter is optional: 
logScores(45, 80);
  1. As expected, if we pass in four scores, we receive Expected 1-3 arguments, but got 4:
logScores(45, 70, 80, 65);

When we have optional parameters, it is likely our function's implementation will need to know which arguments have been passed. We can use the tuple's length property to do this:

  1. Let's create an enhanced version of our scores logger, called logScoresEnhanced, which thanks us if we log all 3 scores:
type Scores = [number, number?, number?];

function logScoresEnhanced(...scores: Scores) {
if (scores.length === 3) {
console.log(scores, "Thank you for logging all 3 scores");
} else {
console.log(scores);
}
}
  1. Now, let's call this function with various parameters:
logScoresEnhanced(60, 70, 75); 
logScoresEnhanced(45, 80);
logScoresEnhanced(95);

If we run the program, we only get thanked after the first call when we pass all three scores.

All the enhancements to tuples in TypeScript 3 allow us to use the rest and spread syntax in a strongly-typed fashion. We'll make use of this feature later in the book, when we work with React components.

主站蜘蛛池模板: 讷河市| 佛教| 顺昌县| 体育| 汨罗市| 尼勒克县| 长宁县| 阳曲县| 嵊州市| 济源市| 弥渡县| 武功县| 桦川县| 祥云县| 涿鹿县| 涿鹿县| 临洮县| 平南县| 晋城| 奈曼旗| 临汾市| 林甸县| 太和县| 宁都县| 肇东市| 霍城县| 盐边县| 当涂县| 马公市| 南郑县| 广丰县| 佳木斯市| 土默特左旗| 泾源县| 蒙山县| 阿鲁科尔沁旗| 同仁县| 杨浦区| 察雅县| 西丰县| 灌阳县|