- 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.
推薦閱讀
- Python概率統(tǒng)計(jì)
- 數(shù)據(jù)庫(kù)程序員面試筆試真題與解析
- Hands-On RESTful Web Services with Go
- Java 11 Cookbook
- 零基礎(chǔ)輕松學(xué)SQL Server 2016
- VMware虛擬化技術(shù)
- Spring Boot企業(yè)級(jí)項(xiàng)目開發(fā)實(shí)戰(zhàn)
- Learning Python Design Patterns
- Mastering Linux Network Administration
- Python機(jī)器學(xué)習(xí)算法: 原理、實(shí)現(xiàn)與案例
- Web App Testing Using Knockout.JS
- Clojure for Java Developers
- Natural Language Processing with Python Quick Start Guide
- Apache Solr PHP Integration
- Python面試通關(guān)寶典