Sling Academy
Home/TypeScript/Array Types in TypeScript: A Complete Guide

Array Types in TypeScript: A Complete Guide

Last updated: January 07, 2024

Introduction

As vernacular as the shanty on the banks of the Mississippi, so is the usage of arrays in the realm of programming. TypeScript, with its sturdy demeanor, offers a delightful twist to the common array, ensuring our collections of elements are as orderly as a steamboat’s ledger.

Basic Array Types

Let us embark upon our journey with the simplest of arrays. Declare your allegiance to a type, and TypeScript shall ensure your array stays true to its promise:

let numbers: number[] = [1, 2, 3];
let strings: Array<string> = ['Mark', 'Livvey', 'Huck'];

One can utilize the syntax of ye olde arrays, or don braces as a knight his armor, with the generic array type.

Using Tuple Types

Imagine a sumptuous feast arrayed with distinct morsels. Tuples in TypeScript permit such an array, allowing a typed sequence with variety abounding:

let mealtimes: [string, number, boolean] = ['Breakfast', 7, true];

The order and type must be adhered to more strictly than a church’s Sunday schedule.

Multidimensional Arrays

Twain might’ve chuckled at the thought of arrays upon arrays, a veritable maze comparable to the depths of the mighty river. Multidimensional arrays are indeed a robust tapestry of data:

let matrix: number[][] = [[1, 2], [3, 4]];

Likened to a double-decker riverboat, one array carries another, each with its own storied cargo.

Read-only and Immutable Arrays

As unchanging as the stalwart character of a noble hero, readonly arrays do not permit the meddling of their contents:

let constantSeas: readonly string[] = ['Atlantic', 'Pacific', 'Arctic'];

Attempting to alter these protected waters will summon TypeScript’s wrath, a compiler error your only spoils.

Union and Intersection Types

A surprising plot twist is at your fingertips with union types, capable of holding various treasures within one chest:

let mixedBag: (number | string)[] = [1, 'Gold', 3, 'Silver'];

While intersection types, akin to steamboat alliances, create a new array monster that bears the strength of all it contains:

let flask: Array<number & { potion: string }> = [/* can't actually be instantiated directly */];

Indeed, a curious concoction, yet workable in the alchemy of types.

Type Inference in Arrays

With a twinkle in its eye, TypeScript infers type like a dapper gentleman deduces a lady’s favor. To explicite types becomes a choice rather than a necessity:

let inference = ['Twain', 1835]; // inferred as (string | number)[]

This clever convenience allows a programmer more freedom than whitewashing fences.

Type Guards and Assertion

TypeScript, with its watchful gaze allows for type guards to be set – sentinels keeping the integrity of your arrays as sacrosanct as a reputable pilot’s reputation:

if (typeof inference[1] === 'number') {
  // TypeScript now knows this is a number
}

And assertion, a confident stride at a riverboat’s helm declaring your type against the current of uncertainty:

let age: any = 'twelve';
(age as number)++; // Assert and sail forth, though it leads to runtime error if age is not a number

Advanced Mappings and Mutable Operations

With the craftsmanship of a seasoned cabinetmaker, TypeScript’s mapped types transform arrays meticulously:

type ReadonlyStrings = ReadonlyArray<string>;

And thou can still mutably navigate your arrays, akin to diverting the current’s course, employing advanced manipulation:

let changingCurrents = ['River', 'Stream', 'Creek'];
changingCurrents.push('Brook');

The operations resemble the deck of a busy steamboat, always shifting, reordering, full of activity.

Conclusion

In conclusion, TypeScript arrays are as varied and as elegant as the storied tales along the riverbanks of old. They lend a robustness to our code that makes it as reliable as a captains log and as functional as a Huck’s raft. Write your arrays well, and your code shall flow like the mighty Mississippi.

Next Article: Tuples in TypeScript: A Complete Guide

Previous Article: Using Nested Object Types in TypeScript

Series: The First Steps to TypeScript

TypeScript

You May Also Like

  • TypeScript: setInterval() and clearInterval() methods (3 examples)
  • TypeScript sessionStorage: CRUD example
  • Using setTimeout() method with TypeScript (practical examples)
  • Working with window.navigator object in TypeScript
  • TypeScript: Scrolling to a specific location
  • How to resize the current window in TypeScript
  • TypeScript: Checking if an element is a descendant of another element
  • TypeScript: Get the first/last child node of an element
  • TypeScript window.getComputerStyle() method (with examples)
  • Using element.classList.toggle() method in TypeScript (with examples)
  • TypeScript element.classList.remove() method (with examples)
  • TypeScript: Adding Multiple Classes to An Element
  • element.insertAdjacentHTML() method in TypeScript
  • TypeScript – element.innerHTML and element.textContent
  • Using element.removeAttribute() method in TypeScript
  • Working with Document.createElement() in TypeScript
  • Using getElementById() method in TypeScript
  • Using Window prompt() method with TypeScript
  • TypeScript – window.performance.measure() method (with examples)