Introduction
Arrays are popular and useful in programming. They allow you to create and store an ordered list of data of different types. An array can contain a mix of numbers, strings, objects, and even other arrays.
Getting comfortable with working with arrays will be beneficial to your programming journey.
Defining Arrays in JavaScript
A common way to create arrays in JavaScript is to use the array literal notation []
. You most likely know this if you have some experience working with JavaScript. Nonetheless, let's see some examples below.
// JavaScript
let numsArray = [1, 2, 3]
let mixArray = [1, "two", "three", 4]
Arrays may contain only values of a particular type like the numsArray
which has only numbers. It can also contain values of multiple datatypes like mixArray
array that has both numbers and strings.
Defining Arrays in TypeScript
To assign a type of array to a variable in TypeScript, you use the following syntax TypeName[]
. You specify the type name followed by square brackets.
For example, taking the earlier numsArray
, here's how you can assign a type to it in TypeScript.
let numsArray: number[] = [1, 2, 3]
When you assign number[]
to numsArray
, it means that the array should only contain numbers. You are not allowed to pass a value that is not a number (eg. a string) to it. If you do, TypeScript will prompt you with an error.
let numsArray: number[] = [1, 2, 3, "hi"]
// Error: Type 'string' is not assignable to type 'number'.
When you add the string "hi" to numsArray
, TypeScript immediately throws an error. The error is informing you that numsArray
can only accept numbers.
What if you want your array to be able to accept more than one type of data? Like the second mixArray
example.
To allow multiple data types, you can use the union type.
The union type allows you to assign multiple types to a variable. For themixArray
, which has both strings and numbers, here's how will assign the types in TypeScript.
let mixArray: (string | number)[] = [1, "two", "three", 4]
The syntax (string | number)[]
indicates that mixArray
accepts both numbers and strings.
To learn more about the union types, read this lesson on union type.
Conclusion
That's all for this lesson! You now know how to work with Array Types in TypeScript.
We considered how to define an array that accepts only one type of data. We also looked at what to do to allow arrays to accept elements of more than one data type.
I hope you found this useful. Thanks for reading.