Member-only story
TypeScript: Define an Array
Arrays in TypeScript allow us to store collections of data while ensuring type safety. Whether you’re working with numbers, strings, or even custom objects, TypeScript arrays provide a clean and intuitive way to enforce the structure and types of the elements. In this post, we’ll walk through how to define arrays in TypeScript and provide examples for specific use cases.
Define an Array in TypeScript
In TypeScript, there are multiple ways to define an array. Each of these approaches allows you to specify the type of elements the array can hold, making your code safe and predictable.
Method 1: Using Square Bracket Notation type[]
This is the most common way to define an array in TypeScript.
let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["Alice", "Bob", "Charlie"];
Here, number[]
means the array can only contain elements of type number
, and string[]
means it can only contain elements of type string
.
Method 2: Using the Array<type>
Generic Syntax
TypeScript provides a generic syntax for defining arrays, which is an alternative to the square bracket syntax.
let numbers: Array<number> = [1, 2, 3, 4, 5];
let names: Array<string> = ["Alice", "Bob", "Charlie"];