The playlist on your phone holds one kind of thing: all songs, and you can keep adding to it. A row on an attendance sheet is different. It always has the same columns, in the same order: the first column is the name, the second is the age. Both shapes of data appear in code all the time, and TypeScript has a type for each.
The playlist is a picture of an array: a list where every item is the same kind of thing. An array's type matches what it holds: string[] means an array where every item is text, however many there are. The attendance row is a picture of a tuple: an array with a fixed number of items, where each position has its own type, like each column in the attendance row. For example, [string, number] for a name and an age.
Array: a list of one kind of thing
Each of the three variables below holds an array. The last two lines try to add items to fruits:
let fruits: string[] = ["apple", "orange", "mango"];
let scores: number[] = [1, 2, 3];
let names: Array<string> = ["Budi", "Ani"];
fruits.push("banana"); // allowed
fruits.push(5);
string[]reads as "array of string": every item is text. Innumber[]every item is a number.Array<string>is another way to writestring[], and it means exactly the same.string[]is the one you'll see more often.fruits.push(5)is rejected:Argument of type 'number' is not assignable to parameter of type 'string'. ts(2345). A number can't go into an array of text.fruits[0]has the typestring, because everything infruitsis text. TypeScript has a setting callednoUncheckedIndexedAccess, andnpx tsc --init(the command that creates TypeScript's settings file) turns it on. When that setting is on, the type offruits[0]isstring | undefined(astringorundefined), because the array might have no item at that index.
Taking the first item in a function
The function getFirst takes an array of text and returns its first item:
function getFirst(arr: string[]): string {
return arr[0];
}
console.log(getFirst(["x", "y", "z"])); // x
console.log(getFirst(fruits)); // apple
arr: string[]: the parameter is an array of text.): string: what comes back is one piece of text, not an array.arr[0]takes the first item of the array that was sent to the function, whatever it holds. Don't writefruits[0]inside the function, because then the result is always"apple".
Tuple: a fixed count and order
profile below is a tuple that holds a name and an age. The last two lines are wrong on purpose:
let profile: [string, number] = ["Budi", 17];
let studentName = profile[0]; // string
let age = profile[1]; // number
let other = profile[2];
profile = [17, "Budi"];
[string, number]means exactly 2 items: position 0 is text, position 1 is a number. TypeScript knowsprofile[0]is astringandprofile[1]is anumber.profile[2]is rejected:Tuple type '[string, number]' of length '2' has no element at index '2'. ts(2493). It means: this tuple has only 2 items, so there's nothing at index 2.profile = [17, "Budi"]is rejected twice, once for each position:Type 'number' is not assignable to type 'string'.andType 'string' is not assignable to type 'number'.So the order is checked too.
A plain array is different. If fruits holds three pieces of text, ["apple", "orange", "mango"], then fruits[3] is still accepted, with the type string. But when the code runs, it holds undefined. The reason: the type of a plain array doesn't record its length. Only a tuple knows how many items it has.
readonly: you can read it, not change it
The word readonly before an array type means the array can only be read. The last two lines below try to change it:
const COLORS: readonly string[] = ["red", "blue"];
COLORS[0]; // reading is fine: "red"
COLORS.map((c) => c + "!"); // fine, it makes a new array
COLORS.push("green");
COLORS[0] = "black";
COLORS.push("green")is rejected:Property 'push' does not exist on type 'readonly string[]'. ts(2339). The methods that change an array (push,pop,sort) aren't there.COLORS[0] = "black"is rejected:Index signature in type 'readonly string[]' only permits reading. ts(2542).readonlyis only checked by TypeScript. In the compiled JavaScript, the wordreadonlyis gone. So if code that still has the error runs anyway, the array really does change.
const and readonly are different: const stops the variable from being given another array, readonly stops the array's items from being changed.
⚠️ Brackets in the wrong place, and a tuple you can still push to
[string]is notstring[].[string]is a tuple with exactly one piece of text.let fruits: [string] = ["apple", "orange", "mango"]is rejected withSource has 3 element(s) but target allows only 1.- A tuple can still be
pushed.profile.push(99)is accepted, even though the tuple has only 2 items. The count is checked when the tuple is filled and when an index is read, not onpush. Want the tuple really locked? Usereadonly [string, number]. - Naming the array outside the function. In the exercise,
getFirstis tested with other arrays, for example["red", "blue"]must give"red". Use the parameterarr, notfruits. - Different items or order. In the exercise,
fruitsmust hold exactly["apple", "orange", "mango"]: three lowercase words, in that order.
TL;DR: An array gets the type string[], number[] or Array<string>: one kind of item, any number of them, and an item of another type is rejected (ts(2345)). A tuple, such as [string, number], is an array with a fixed count and its own type at each position. An index past a tuple's length is rejected (ts(2493)), while a plain array accepts an index past its length, and when the code runs that item is undefined. readonly string[] is an array that can be read and mapped, but push and replacing items are rejected. readonly is only checked before the code runs. To return the first item of the array sent in through the parameter arr, write return arr[0];.
⚡ Array: one kind of thing
Write:
let fruits: string[] = ["apple", "orange", "mango"];
fruits.push("banana"); // allowed
fruits.push(5);
Meaning: string[] is the type of an array where every item is text, however many there are. So fruits.push(5) is rejected. Careful, [string] is different: that's a tuple (an array with a fixed number of items) holding exactly one piece of text.
⚡ Tuple: a fixed count and order
Write:
let profile: [string, number] = ["Budi", 17];
let other = profile[2];
profile = [17, "Budi"];
Guess first: the tuple [string, number] holds exactly two items, at positions 0 and 1. Does TypeScript accept profile[2]?
Rejected: Tuple type '[string, number]' of length '2' has no element at index '2'. A tuple knows how many items it has. A plain array doesn't. If fruits holds only three pieces of text, fruits[3] is still accepted, even though it holds undefined.
Meaning: [string, number] means exactly 2 items: position 0 is text, position 1 a number. The order is checked too, so [17, "Budi"] is rejected.
⚡ readonly: read it, don't change it
Write:
const COLORS: readonly string[] = ["red", "blue"];
COLORS[0]; // allowed
COLORS.push("green");
Meaning: readonly before an array type means the array can only be read. Methods that change an array, like push, aren't available on a readonly array. const stops the variable from getting a different array, readonly stops the array's contents from changing.