Arrays
Arrays have types too. An array of texts has the type string[] (read “an array of strings”), an array of numbers number[]: the type of the elements, followed by square brackets. Usually, TypeScript infers it from the elements:
const inventory = ["Healing Potion", "Silver Sword"]; // string[]
const prices = [15, 45]; // number[]From the type, TypeScript knows two things. Every element of inventory is a string, so inventory[0].toUpperCase() is fine. And only texts may go in:
const inventory = ["Healing Potion", "Silver Sword"];
inventory.push(20);main.ts(2,16): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.push is a method, a function that belongs to the array, and 20 is its argument, the value in the parentheses. The argument goes into the method's parameter, and for an array of texts, that parameter has the type string. A number doesn't fit there.
You can also write the type of an array as an annotation: const prices: number[] = [15, 45];. With elements, it isn't needed. It is needed for an empty array. From [], TypeScript can't tell what will go in, so it tries to work it out from what the program pushes, and it lets everything in:
const loot = [];
loot.push("Gold Ring");
loot.push(5);
console.log(loot);This program runs without an error and prints ["Gold Ring", 5]. In other programs, TypeScript gives up instead and reports Variable 'loot' implicitly has type 'any[]' in some locations where its type cannot be determined. (You'll learn about any at the end of this lesson.) So give an empty array its type:
const loot: string[] = [];
loot.push("Gold Ring");
loot.push(5);main.ts(3,11): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.Typical mistake: const loot: [] = [];. The type [] without anything before it means an array that is always empty, so nothing can be pushed into it: Argument of type '"Gold Ring"' is not assignable to parameter of type 'never'. (never is a type that has no values at all.) Write the type of the elements before the brackets: string[].
Instructions
Kira has found 20 arrows, but the inventory holds the names of items, so TypeScript won't let the number in. Replace 20 with the text "Arrows", so that the program prints:
["Healing Potion", "Silver Sword", "Old Key", "Arrows"]Kira opens a chest. At the end of the program, create an empty array loot for the names of the items in the chest, with the type string[].
Push "Gold Ring" and "Dragon Scale" into loot and print the array, so that the program also prints:
["Gold Ring", "Dragon Scale"]Start programming for free
5/9