- 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.
推薦閱讀
- Mastering RabbitMQ
- Learning AWS Lumberyard Game Development
- Magento 2 Development Cookbook
- C語言程序設計
- Python機器學習算法: 原理、實現與案例
- Hands-On Neural Network Programming with C#
- Android Development Tools for Eclipse
- SpringBoot從零開始學(視頻教學版)
- Oracle Database XE 11gR2 Jump Start Guide
- Solr權威指南(下卷)
- 零基礎學Java第2版
- 深入理解Java虛擬機:JVM高級特性與最佳實踐
- Python高性能編程(第2版)
- Processing開發實戰
- Android開發權威指南(第二版)