TypeScriptLesson 3 of 16
Arrays and tuples
An array holds any number of values of one type. A tuple is a fixed-length array where every position has its own type.
Key points
- Two ways to write the same type: number[] and Array<number>.
- A string cannot go into a number array: push("ten") is flagged as an error.
- The tuple [string, number] has exactly two items: a string, then a number.
- A tuple is easy to unpack into variables: const [name, age] = entry.
Example
const scores: number[] = [7, 9, 10];const tags: Array<string> = ["ts", "web"];scores.push(8);// scores.push("ten"); // error: string is not assignable to number const point: [number, number] = [3, 4];const entry: [string, number] = ["Anna", 25];const [who, age] = entry; console.log(`Scores: ${scores.join(", ")}; tags: ${tags.length}`);console.log(`${who} is ${age}, point x = ${point[0]}`);scores.push(8) works, push("ten") does not. The tuple entry is unpacked into two variables, and each keeps the right type: who is a string, age is a number.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Type the cart as [string, number][], loop over it with for...of, print every item as "Coffee: 4" and finish with "Total: 12".
Output
What your program prints appears here.