

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Tuples
incomplete
2: Readonly
incomplete
3: Tuples vs. Objects
incomplete
4: Destructuring Tuples
incomplete
5: Named Tuples
incomplete
6: Optional Elements in Tuples
incomplete
7: Tuple Rest Elements
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
TypeScript allows tuples to have a variable number of elements of a specific type using rest elements. This is nice when you want a tuple to have a fixed-length beginning but a flexible-length ending:
// A tuple with a rest element
type NameAndScores = [string, ...number[]];
// All of these are valid
const nameAndScores: NameAndScores = ["Alphonse", 69, 420, 300];
const nameAndScores: NameAndScores = ["Winry", 42];
const nameAndScores: NameAndScores = ["Edward"];
This idea of flexibly sized tuples honestly barely feel like tuples to me... it feels like arrays with some type constraints... but I digress.
One great use case for rest elements would be to model a command line argument pattern:
type Command = [name: string, ...args: string[]];
const gitCommit: Command = ["git", "commit", "-m", "Add new feature"];
const npmInstall: Command = ["npm", "install", "typescript"];
// Function that handles commands
function executeCommand([cmd, ...args]: Command) {
console.log(`Executing ${cmd} with arguments: ${args.join(", ")}`);
}
It says "I need a command string, but everything after that is optional". Pretty neat. Remember, the whole point of a great type system is to more accurately (and narrowly) model the valid states of your program.
LLMs process tokens to understand inputs and generate outputs. They are kind of like words, and for the sake of this lesson, we'll just assume they are.
Complete the tokenize function. It takes an input string and returns a [number, ...string[]] tuple, where the first element is the cost of the tokens and the rest are the tokens themselves.
The .split() method splits a string into an array of substrings based on a specified separator.
To return the tokens after the cost, spread the token array into the returned tuple.