Arrays in TypeScript, a starters guide. [“hip”, “hip”]

Like many bootcamp graduates, I was taught JavaScript, which is the language for development on the web. JavaScript has many flaws but one that drives us developers bonkers, is that we only catch errors during run-time because JavaScript is an interpreted language. Through a recommendation from a friend, many job postings and that one guy from, I dove into a Udemy course on TypeScript.

What is TypeScript you may ask? Great question… “TypeScript is a superset of the JavaScript language that has a single open-source compiler and is developed mainly by Microsoft. The goal of TypeScript is to help catch mistakes early through a type system and to make JavaScript development more efficient.”

Your next question might be, “but Joe, what does that even mean?” Another great question… We’ll first start off with what a superset is. A superset, in computer science terms is, “A programming language that contains all the features of a given language and has been expanded or enhanced to include other features as well.” To make sense of that, let’s explore an easy to grasp example. Let’s think of JavaScript as an iPhone 12 and TypeScript as an iPhone 12 Pro Max. Both are great phones and get the job done, but the iPhone 12 Pro Max has a bigger screen, better storage options, better cameras, and a better battery life. See what I mean?

Next we’ll go over what a type is and what the TypeScript type system is.

A type is, “an attribute associated with a piece of data that tells a computer system how to interpret its value.” A few types we developers have are as followed. An integer, which refers to a whole number, examples: 4, 40, and 100. A float, which refers to a number that has a decimal point, examples: 8.99, 10.50, and 3.1415. A string, which refers to any characters wrapped in quotation marks “”, examples: “Joe”, “Hello world”, and “123456789”. A boolean which refers to a true or false value, examples: isCold: false, or iHateTheCold: true, it’s how we developers describe if something is on or off, yes or no. And the main topic of my blog an array, any of the types above wrapped in these [ ] symbols. For example, [“Joe”, 28, true]

What is TypeScripts type system? TypeScript’s type system provides for specifying and inferring types, with type inference, as well as setting types as optional, with type annotation. The optional setting allows you to choose when to enforce types and when to allow dynamic types. To opt out of type checking, you can use the any keyword, but we do want to avoid that.

TypeScript is statically typed and, therefore, all checks are performed at compile time, or when as I like to say, when you’re writing the code. The compiler checks all variables and expressions against their types, and removes all type information when it converts the code into valid JavaScript.

Now with the basics out of the way, let’s talk about arrays. Arrays are pretty important in programming, actually… really important.

Working with arrays in TypeScript is just like working with arrays in JavaScript, with one important caveat. We generally only put elements of the same type in the array. We can put different types in the same array but you must be very explicit about it, and use a special type annotation. We will look at that later.

They are used for storing lists of related information. Think of an array as a grocery list. On your list you have, Bread, Milk, Eggs, and Coffee. This is represented in the image below. Here we told TypeScript that groceryList is an array with strings. This was done by right after declaring groceryList, ( string[] )

This is an example of Type annotation. We are explicitly telling TypeScript this is an array of strings.

Below is an example of TypeScripts, type inference.

You will see type inference at work on line 7, ( let groceryList: string[] ) TypeScript did the work for us and it knows that this array will contain strings.

Let’s get started….

If we initialize an empty array, we want to annotate it with its expected types.

If we initialize an array with values inside of the array, type annotation is not needed because type inference will kick in.

Now for the really awesome stuff!!

TS can do type inference when extracting values from an array

If we hover over the variable mostImportant, TypeScript will use type inference and and say this new variable is of type string. Pretty neat!!

Ts can prevent us from adding incompatible values to the array

As you can see, we get an error when trying to insert the number 300, into the groceryList array. For anyone who doesn’t code, .push() is an array method that adds an element to the end of the array. Notice it catches the error right away. We get the error message, “Argument of type ‘number’ is not assignable to parameter of type ‘string’. ” This error is basically telling us, you’re trying to insert a type of number into an array that only is supposed to have type string. To catch a bug like this, as you’re writing your code, saves so much time and debugging effort.

We get help with ‘.map’, ‘forEach’, ‘.reduce’ functions.

Again for those who don’t code, ‘.map()’ is another array method that creates a new array with the results of calling a function for every element in the array. We iterate through the groceryList array, assigning each element to the variable grocery, which is of type string. Different types have different built-in functions and methods. Strings have different built-in methods and functions then numbers and arrays.

Then on line 17, we say ( return grocery. ) after we type the period, we get all the methods and functions that a string has. For example, toLowerCase and toUpperCase. I bet you can tell what those do…

Flexible: Arrays can still contain multiple different types

If we hover over differentTypes, on line 14 we can see type inference show that we have types (string | number | boolean )[] in our array. The ( | ) symbol represent the word “or.” So we would read the line 14 as, “The array can contain types of ‘string or number or boolean’ .

What if we wanted to initialize a new array with no values or maybe just one? How would we be able to insert different types into that array? Easy, the special type annotation I said we would talk about earlier.

As you can see above, we only have a string in the array. We want to use the same annotation as we did above. After we declare the variable differentTypes, we add the annotation (string | number | boolean )[]. After we declare the variable. This tells TypeScript, HEY! This array can receive, types of string, number, and boolean but nothing else, unless it’s specified. You will see what I’m talking about in the picture below, when it gives us an error for trying to .push() the new Date() into the differentTypes array.

If we hover our mouse over the new Date(), we will get the error message, “Argument of type ‘Date’ is not assignable to parameter of type ‘string | number | boolean’. Type ‘Date’ is not assignable to type ‘number’.” This error is telling us we can not add of type Date to our array because it is not of type, (string | number | boolean ). We will talk about the Date type in another blog, I promise…

I hope this helps you get up and running with TypeScript. I can’t wait to see where it takes us and what it will help us build. All the best in your journey.


Full stack developer, tech junkie, @self , and ran-bob on the internet.