constanimals:string[] = ['Pangolin','Penguin','Porcupine'];animals[4] ='Platypus';// OKanimals[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>:
...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:
letinventoryItem: [string,number];inventoryItem= ['🐄',51];// OKinventoryItem= ['🐄','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:
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 stringornumber:
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'