TypeScript
  • Introduction
  • Introduction
    • What is TypeScript?
    • Why TypeScript?
    • Setup
  • Beginner
    • Basic types
      • Primitive types
      • Arrays and tuples
      • Enums
      • Any type
    • Objects
    • Type aliases
    • Interfaces
    • Functions
      • Function signatures
      • Void type
      • Functions as types
    • Union types
    • Type guards
    • Intersection types
    • Nullable types
    • Inference
  • Resources
    • Resources
Powered by GitBook
On this page
  • Arrays
  • Tuples
  1. Beginner
  2. Basic types

Arrays and tuples

Arrays

const animals: string[] = ['Pangolin', 'Penguin', 'Porcupine'];
animals[4] = 'Platypus'; // OK
animals[5] = false; // Error: a boolean is not assignable to type 'string'

This can also be done a second way using the generic array type, Array<elemType>:

const animals: Array<string> = ['Pangolin', 'Penguin', 'Porcupine'];

...but you can mostly ignore this for now, because: (a) Generics are an advanced topic that we’ll cover later, and (b) this is not the Shopify-preferred way for indicating array types anyway.

Tuples

A tuple is a general way of grouping together some number of other values with a variety of types into one compound type. Each position in the tuple has a type, and the types of the different values in the tuple don’t have to be the same.

For example:

let inventoryItem: [string, number];
inventoryItem = ['πŸ„', 51]; // OK
inventoryItem = ['πŸ„', '51']; // Error: '[string, string]' is not assignable to type '[string, number]'
inventoryItem = [51, 'πŸ„']; // Error: '[number, string]' is not assignable to type '[string, number]'

When accessing an element with a known index, the correct type is retrieved:

console.log(typeof inventoryItem[0]); // "string"
console.log(typeof inventoryItem[1]); // "number"

When accessing an element outside the set of known indices, a union type is used instead. Union types are a topic that we’ll cover in depth later, but if we use a simplified definiton, they can be said to apply an "OR" condition to each type in the set of types.

In this example, the union type string | number can have assigned to it any value of type string or number:

inventoryItem[3] = '🐐'; // OK
inventoryItem[4] = 7000; // OK
inventoryItem[5] = true; // Error: a boolean isn't assignable to type 'string | number'
inventoryItem[6] = 'Hello';
inventoryItem[6].replace('🐐', 'goat'); // Error: Property 'replace' does not exist on type 'string | number'
PreviousPrimitive typesNextEnums

Last updated 6 years ago