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

Spread expressions

TypeScript 3 allows us to use tuples with spread expressions.

Let's look at an example:

  1. Let's go back to the problematic pure JavaScript example we looked at for using the spread syntax:
function logScore(score1, score2, score3) {
console.log(score1 + ", " + score2 + ", " + score3);
}

const scores = [75, 65, 80];

logScore(...scores);

The TypeScript compiler raised the error Expected 3 arguments, but got 0 or more.

  1. Let's resolve this now with enhanced tuples in TypeScript 3. We'll start by adding types to the function parameters:
function logScore(score1: number, score2: number, score3: number) {
console.log(score1, score2, score3);
}

   There's nothing new yet, and we're still getting the compilation error.

  1. Let's change the scores variable into a fixed tuple:
 const scores: [number, number, number] = [75, 65, 80];

That's it – the compilation error has gone! All we needed to do was tell the compiler how many items were in scores for it to successfully spread into the logScore function.

So, in TypeScript 3, we can spread into fixed tuples. What about open-ended tuples? Let's give that a try:

const scoresUnlimited: [...number[]] = [75, 65, 80];

logScore(...scoresUnlimited);

Unfortunately, the compiler is not yet quite clever enough to let us do this. We get the compilation error Expected 3 arguments, but got 0 or more.:

主站蜘蛛池模板: 阿拉善右旗| 鹤壁市| 盖州市| 峡江县| 汪清县| 荃湾区| 资源县| 新宁县| 长乐市| 彰化县| 韶关市| 南康市| 博湖县| 柳江县| 视频| 赤壁市| SHOW| 海林市| 监利县| 萨嘎县| 崇明县| 额济纳旗| 绥化市| 剑阁县| 右玉县| 溆浦县| 扶绥县| 东宁县| 兰溪市| 钦州市| 革吉县| 从江县| 麻江县| 彭州市| 简阳市| 浦北县| 尤溪县| 贡山| 秦安县| 山阴县| 贵德县|