DEV Community

loading...

Typescript: Array Types & Usage

Brad Beggs
Curious and Persistent.
・3 min read

Assumptions

  • You know what Typescript is for.
  • You have it installed.
  • You can format basic data types (number, string, boolean)

JS arrays are useful containers, holding whatever is asked. But over time one might add the wrong data type into it and get away with it until the bug presents.

Typescript arrays on the other hand are a bit rigid. But this initial rigidity is helpful over time, particularly on a team. The TS array declaration speaks of its intent, unlike the JS version.

Basic Array Type Usage

The basic declaration of an array data type is straight forward:

let arrayName: number[] = [ ]   // initialize arrayName with blank array, holding only floating point numbers 

let animals: string[] = [dog, cat, mouse] // initialize animals with a string of names and only strings
Enter fullscreen mode Exit fullscreen mode

If you try to put a string into the array 'arrayName', TypeScript will kindly tell you can't.

But what if you need an array with multiple types?

Multiple Data Types in Array & Nested Array

But if your array requires multiple data types, you can specify which types it should accept using ‘|’ :

let greetingCountDown: string[] | number[] = [1,2,3, hello];

let date:  (Date | string | number ) = [new Date(), appt, 1032]; // a 1 dimension array, allowing uses of dates, strings and numbers

let dateTwo:  (Date | string[] | number)[] = [new Date(), 1032, ["brad", "dog", "vote"]];  // a 2 dimensional array with nested array of strings. 'string[]' indicates a subarray in this usecase

Enter fullscreen mode Exit fullscreen mode

Note: the ‘|’ is called the ‘union’ operator in TS.

Handling Unknown Array Data Types

If you’re fetching from an API or using a library, you might not know or have control of the data.

To show the intention of allowing any data type, declare your type as ‘any’:

let result: any = [] // initialize result to allow any and all datatypes
Enter fullscreen mode Exit fullscreen mode

Why not just declare ‘let result = []’ and drop the use of ‘: any’? Declaring type communicates intent to other developers and your IDE.

Array of Objects in TypeScript

There are two ways to declare an array of objects: inline and via ‘interface’.

The inline method is simple but cumbersome and the object isn’t readily reusable elsewhere.

The inline format looks like this:

let arrayName: {objectDeclarationHere}[] = [ { } ]  // initialize blank array of objects  
Enter fullscreen mode Exit fullscreen mode

Inline example:

// declare an inline array of objects
const peopleShirtArray: {
  name: string;
  shirtSize: "small" | "medium" | "large";
}[] = [
  { name: "Brad", size: "small" },
  { name: "Kamala", size: "medium" },
  { name: "Amanda", size: "large" },
  {name: Cacilda, size:medium},
];
Enter fullscreen mode Exit fullscreen mode

The interface method once set up, is mostly straightforward. There are details worth reading up on if you need to reuse your object.

The interface format:

// declare the interface
// export the interface; the interface is often placed in a separate file for reuse  
// export is optional though

export interface peopleShirts {
Name: string,
size: "small"; |  medium; |   large;
}


// declare your import 
import { peopleShirts } from '../api/responses';

// declare the array of objects with the interface 
const peopleShirtArray: peopleShirts = [
  { name: "Brad", size: "small" },
  { name: "Kamala", size: "medium" },
  { name: "Amanda", size: "large" },
  {name: Cacilda, size:medium},
];
Enter fullscreen mode Exit fullscreen mode

The interface article listed in the Resources is excellent, with useful code examples and analogies for understanding.

Resources

Feedback?

Have thoughts or advice for others on array data types and interfaces in TypeScript?

If so, drop a note. I'd love to hear and see your examples, explanations, and other details to clarify how/why/when.

Discussion (0)