Learn TypeScript in Construct, part 10: Data structures

UpvoteUpvote 3 DownvoteDownvote

Index

Features on these Courses

Stats

58 visits, 62 views

Tools

Translations

This tutorial hasn't been translated.

License

This tutorial is licensed under CC BY-NC 4.0. Please refer to the license text if you wish to reuse, share or remix the content contained within this tutorial.

Published on 25 Jul, 2025.

This tutorial series is still under development

This is part 10 of the tutorial series Learn TypeScript in Construct. This part continues on from part 9. So in case you missed it, see Learn TypeScript in Construct, part 9: Object methods.

In this part we'll continue using an empty script file in a new Construct project as we've done for the past few tutorials. It's time to learn about a couple more data structures in TypeScript. These data structures are used in most other programming languages, but we'll learn how to use them in TypeScript specifically.

Arrays

An array is a list of values. Values in the array are also called elements. The elements can be any type - strings, numbers, objects, even functions and other arrays. To keep things simple we'll focus on just using strings at first.

Similarly to how objects can be created with { and }, arrays can be created with [ and ], with a list of values separated by commas. Note that we don't have property names here, just values.

let myArray = ["pizza", "noodles", "burrito"];

// Show this array in the console
console.log(myArray);

The above example creates an array with three string elements: "pizza", "noodles" and "burrito". It logs the array to the console so you can inspect it similarly to viewing objects - and note you may need to click an expand button to see the elements inside the array.

The type of an array depends on the type of thing it stores. In this case, the array consists entirely of strings, and its type is string[]. The [] indicates it's an array, and the string is the type of the elements of the array.

Arrays also have some built-in properties which can be accessed with a dot like object properties. The length property has the number of elements, which in this case is 3.

let myArray = ["pizza", "noodles", "burrito"];

console.log(`The array length is ${myArray.length}`);

Each element in array is numbered with an index. This starts from zero - most things in programming actually use a zero-based index, so the first item is numbered 0 rather than 1. This might seem odd, but makes sense given how things work internally (which in the interest of simplicity we won't go in to here).

In the previous example the array has three elements with the following indices:

  • Element 0 is "pizza"
  • Element 1 is "noodles"
  • Element 2 is "burrito"

Individual elements can be accessed using square brackets after the array, such as myArray[0] to access the first element with index 0. Note this usage is different to creating an array - in this context the square brackets mean to read an element.

let myArray = ["pizza", "noodles", "burrito"];

console.log(`Element 0 is ${myArray[0]}`);
console.log(`Element 1 is ${myArray[1]}`);
console.log(`Element 2 is ${myArray[2]}`);

Note one important detail: the last element has an index of 2, which is one less than the length of 3. This is because it uses a zero-based index.

Array elements can also be assigned to change them, similarly to how variables work.

let myArray = ["pizza", "noodles", "burrito"];

// Change the second element (at index 1)
myArray[1] = "chocolate";

console.log(`Element 0 is ${myArray[0]}`);
console.log(`Element 1 is ${myArray[1]}`);
console.log(`Element 2 is ${myArray[2]}`);

Remember that with this array, the elements have a string type. Therefore you cannot assign a number to an array element. As ever, TypeScript enforces consistent use of types across all your code.

Iterating an array

Arrays can be any size. So if you want to do something like log every element to the console, we'll need a for loop that repeats once per element, up to the array length. The example below demonstrates this.

let myArray = ["pizza", "noodles", "burrito"];

// Repeat once for each element in the array
for (let i = 0; i < myArray.length; i++)
{
	console.log(`Element ${i} is ${myArray[i]}`);
}

This will repeat the console log with i having the values 0, 1 and 2 - which matches up with the element indices. Note the loop condition tests that i is less than the array length - not less than or equal - since as we mentioned previously, the last array element has an index one less than the length.

Another way to do this is with a different type of loop that TypeScript provides, called a for..of or "for-of" loop. Instead of three statements to manage a variable in the loop, it uses the of keyword. The example below demonstrates this.

let myArray = ["pizza", "noodles", "burrito"];

// Repeat once for each element of myArray
for (let elem of myArray)
{
	console.log(`The array element is ${elem}`);
}

In this form, the loop declares a variable named elem, which TypeScript infers has a type of string as that is the type of the array elements. The loop then automatically repeats once for every element of myArray, with the loop variable elem set the value of the current element. So this loop will also log a message with each element to the console.

This type of loop is a bit more convenient to write, as you don't need to include comparison or increment parts of the loop. However note it does not directly provide a way to identify the current index - it only gives the actual values. So in some cases if you still need to know the array index in the loop, such as to read from two same-sized arrays simultaneously, it can be more convenient to use the previous kind of for loop.

For-of loops also work with other things in TypeScript, and in fact the details of how they work goes in to a fairly complex area of TypeScript known as iterators. We won't go in to that here, but it's worth knowing that for-of loops are another way to do something for every element in an array.

Adding and removing elements

TypeScript provides lots of ways to alter arrays, including adding, removing and replacing elements. In the interest of simplicity, we'll just cover two here.

You can use the built-in array push() method to add a new element to the end of an array. Let's also use some emojis for strings!

let myArray = ["😀", "👽", "👾"];

// Add a new element at the end of the array
myArray.push("🤖")

// Show the array in the console
// It now has: 😀, 👽, 👾, 🤖
console.log(myArray);

Once an element is added, the length property automatically increases to 4 to reflect the new size of the array.

In TypeScript if you want to start with an empty array and then push to it, it's important to note that TypeScript will infer the type of an empty array as any[]. That means the type of elements is any and so you can add anything you like to the array.

// Create an empty array.
// TypeScript infers the type as any[].
let myArray = [];

// Both types OK
myArray.push("😀");
myArray.push(5);

console.log("myArray is: ", myArray);

As the main purpose of TypeScript is to use specific types, you should generally avoid doing this. Instead in this case you can use a specific type annotation for the variable, enforcing that it can only store the intended type - in this case strings.

// Create an empty array.
// Use an explicit type to enforce string elements.
let myArray: string[] = [];

myArray.push("😀");

// This is now an error: the array contains strings
// and does not allow numbers.
myArray.push(5);

The second array method we'll cover here is the pop() method. This removes the last element from the end of the array, and also returns the value of the element it removed.

let myArray = ["😀", "👽", "👾"];

// Remove element from end of array
let removedElem = myArray.pop();

// Show the array in the console
// It now has: 😀, 👽
console.log("The array has: ", myArray);

// Show the removed element in the console (👾)
console.log(`The removed element is: ${removedElem}`);

After removing an element the array length property automatically decreases to 2.

A few more details

Back in part 8, we covered how strings and numbers are passed by value, but objects are passed by reference. Arrays are also passed by reference in TypeScript. (In fact, as noted previously, in TypeScript arrays are special kinds of objects.)

Arrays are a type of collection, which is the name given for data structures that store multiple values. Arrays are also an ordered collection, since elements have a clear order and you can tell if one element comes before or after another - and the order can be changed (although we didn't cover that here). This is in contrast to other data structures that may not have a specific ordering or cannot be re-ordered.

Arrays have a lot more features in TypeScript. They're another key fundamental part of programming, and so have a wide range of capabilities that make them flexible and useful for lots of tasks. We'll come back to a few more of these features later in this guide. However we've covered the basics of arrays, and to keep things simple we'll move along.

  • 0 Comments

Want to leave a comment? Login or Register an account!