Start learning free

LESSON 94 OF 348 · ARRAYS I

Arrays in TypeScript: Declaring string[] and number[]

Lesson Read the full explanation

When we're dealing with large amounts of data, we want to make sure we can organize and manage it properly.

In TypeScript, we use arrays to store several pieces of data in one place.


Array Declaration / Creation:

You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry, like this:

let sandwich = ["peanut butter", "jelly", "bread"]

In this program we created an array consisting of 3 string items: "peanut butter", "jelly" and "bread".

Then, we stored that array in a variable sandwich so we can later access it. For example, I can print the array:

// Creating the array:
let sandwich = ["peanut butter", "jelly", "bread"];

// Printing the array:
console.log(sandwich); // Output: ["peanut butter", "jelly", "bread"]

Items Data Types

Arrays can store any data types (strings, integers, booleans, etc.) and the items shouldn't necessary be of the same data type. For example:

let myArray = ["Hello world!", 32, False];

myArray consits of one string item, one number item and one boolean item.

We use arrays to better organize pieces of data which are part of the same family or share the same meaning, like the name of our friends or the items in a sandwich.

So most of the time we will have arrays where the items share the same data type.


Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    TYPESCRIPT · ARRAYS I

    Arrays in TypeScript, explained

    What an array is

    A program often has to handle many related values: the names of friends, the prices in a cart, the ages of a group. Creating one variable per value doesn't scale, and the code can't loop over them. An array stores an ordered list of values under one name. Each value is an element, and the elements keep the order in which you wrote them.

    Creating an array

    An array literal starts with [, ends with ] and separates the elements with commas:

    let sandwich = ["peanut butter", "jelly", "bread"];
    console.log(sandwich);
    
    [ 'peanut butter', 'jelly', 'bread' ]
    

    This array has three strings. Node prints strings inside an array with single quotes, and puts spaces just inside the brackets. The variable sandwich lets you use the array later. The number of elements is available as sandwich.length, here 3. An empty array is written [].

    Array types

    TypeScript adds a type to an array: the element type followed by [].

    • string[] is an array of strings.
    • number[] is an array of numbers. There is one numeric type, number, for whole numbers and decimals alike.
    • boolean[] is an array of booleans.

    You can write the type yourself, or leave it out and let TypeScript infer it from the literal. let sandwich = ["peanut butter", "jelly", "bread"]; is inferred as string[]. Writing the annotation makes the intent explicit and gives clearer errors when the contents are wrong. Once an array has the type string[], adding a number is a compile error:

    let fruits: string[] = ["mango", "kiwi", "grapefruit"];
    fruits.push(5);
    
    error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
    

    This check exists only at compile time. The annotation disappears in the JavaScript that tsc writes. Because tsc still writes the file after reporting an error, a program with such a mistake would run, and the number would end up in the array. Treat compiler errors as problems to fix, even when the program appears to run.

    Mixed arrays

    JavaScript arrays can mix types, and so can TypeScript's. For let myArray = ["Hello world!", 32, false];, TypeScript infers an array whose elements are a string, a number or a boolean, written (string | number | boolean)[]. Note that the boolean literal is lowercase: false, not False. Mixed arrays are legal, but most arrays you write hold one kind of value, because values that are part of the same family are easier to process together. When you do need a fixed shape, such as a string followed by a number, TypeScript has tuple types like [string, number], which are a separate topic.

    Gotchas

    • Brackets after the type, not before. The type is number[]. An annotation like []number is a syntax error.
    • Commas, not spaces. Elements are separated by commas. A missing comma is a syntax error.
    • const does not freeze the contents. With const list = [1, 2] you can't reassign list, but you can still change what is inside it. That comes up in the later lessons.
    • Arrays are objects. typeof sandwich is "object". Use Array.isArray(sandwich) to ask whether something is an array.

    The lesson's exercise

    The exercise has two declarations.

    1. Create fruits. Declare a string[] named fruits holding "mango", "kiwi" and "grapefruit". The annotation : string[] tells TypeScript that every element is a string.
    2. Create ages. Declare a number[] named ages holding 14, 32, 50 and 21. All four ages are now managed as one unit.
    let fruits: string[] = ["mango", "kiwi", "grapefruit"];
    let ages: number[] = [14, 32, 50, 21];
    

    The exercise prints nothing. The two arrays are used in the next lessons, where you read and change their elements.

    Key takeaways

    • An array stores an ordered list of values in one variable, written with square brackets and commas.
    • The type of an array is the element type followed by []: string[], number[].
    • TypeScript infers the type from the literal, and checks it at compile time only.
    • Arrays can mix types, but most of the time the elements share one type.
    • The size of an array is its length property.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free