- Learn React with TypeScript 3
- Carl Rippon
- 195字
- 2021-06-10 19:16:42
Tuple function parameters
Tuple function parameters in TypeScript 3 allow us to create strongly-typed rest parameters.
Time for an example:
- When we first looked at rest parameters, we created a pure JavaScript version of logScores that collected an unlimited amount of arguments in a scores variable:
function logScores(...scores) {
console.log(scores);
}
- In TypeScript 3, we can now make this example strongly-typed with a tuple rest parameter. Let's give this a try in the TypeScript playground:
function logScores(...scores: [...number[]]) {
console.log(scores);
}
- Let's call our function with some scores:
logScores(50, 85, 75);
We don't get a compiler error, and if we run the program, we get an array containing 50, 85, 75 output in the console.
We can create an enhanced version of our function that uses the Scores type from the Open-ended tuples section.
- The function will take in the name, as well as an unlimited set of scores:
type Scores = [string, ...number[]];
function logNameAndScores(...scores: Scores) {
console.log(scores);
}
- Let's try to call our function with some scores from Sally:
logNameAndScores("Sally", 60, 70, 75, 70);
If we run the program, Sally and her array of scores will be output to the console.
推薦閱讀
- Go Web編程
- Java程序設(shè)計(jì)(慕課版)
- 國(guó)際大學(xué)生程序設(shè)計(jì)競(jìng)賽中山大學(xué)內(nèi)部選拔真題解(二)
- Building Cross-Platform Desktop Applications with Electron
- Python高效開發(fā)實(shí)戰(zhàn):Django、Tornado、Flask、Twisted(第3版)
- 零基礎(chǔ)學(xué)Python網(wǎng)絡(luò)爬蟲案例實(shí)戰(zhàn)全流程詳解(入門與提高篇)
- Unity 3D腳本編程:使用C#語(yǔ)言開發(fā)跨平臺(tái)游戲
- 計(jì)算機(jī)應(yīng)用基礎(chǔ)教程(Windows 7+Office 2010)
- Cocos2d-x by Example:Beginner's Guide(Second Edition)
- Solutions Architect's Handbook
- Advanced Python Programming
- INSTANT JQuery Flot Visual Data Analysis
- Scratch編程從入門到精通
- Android 5從入門到精通
- 軟件測(cè)試項(xiàng)目實(shí)戰(zhàn)之功能測(cè)試篇