- 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.:
推薦閱讀
- TypeScript入門與實(shí)戰(zhàn)
- Flask Blueprints
- R語言經(jīng)典實(shí)例(原書第2版)
- 軟件測試工程師面試秘籍
- Django Design Patterns and Best Practices
- Java游戲服務(wù)器架構(gòu)實(shí)戰(zhàn)
- Mastering ServiceNow(Second Edition)
- Visual Basic程序設(shè)計(jì)實(shí)驗(yàn)指導(dǎo)(第二版)
- Learning R for Geospatial Analysis
- Python深度學(xué)習(xí)原理、算法與案例
- C專家編程
- Building Wireless Sensor Networks Using Arduino
- Getting Started with Python and Raspberry Pi
- 信息學(xué)奧林匹克競賽初賽精講精練
- 絕密原型檔案:看看專業(yè)產(chǎn)品經(jīng)理的原型是什么樣