- Learn React with TypeScript 3
- Carl Rippon
- 225字
- 2021-06-10 19:16:42
Spread expressions
TypeScript 3 allows us to use tuples with spread expressions.
Let's look at an example:
- 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.
- 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.
- 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.:
推薦閱讀
- Java Web開發(fā)學(xué)習(xí)手冊
- Node.js 10實戰(zhàn)
- Learning Cython Programming(Second Edition)
- JavaScript by Example
- iOS編程基礎(chǔ):Swift、Xcode和Cocoa入門指南
- Python算法從菜鳥到達人
- Hands-On Automation Testing with Java for Beginners
- Go并發(fā)編程實戰(zhàn)
- 常用工具軟件立體化教程(微課版)
- Visual C#.NET Web應(yīng)用程序設(shè)計
- C語言程序設(shè)計習(xí)題與實驗指導(dǎo)
- Mastering Concurrency Programming with Java 9(Second Edition)
- 計算機應(yīng)用技能實訓(xùn)教程
- Python無監(jiān)督學(xué)習(xí)
- 一步一步學(xué)Spring Boot:微服務(wù)項目實戰(zhàn)(第2版)