Typed Arrays – Arrays where each element is some consistent type of value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const carMakers: string [] = ['ford', 'toyota', 'chevy']; const dates = [new Date(), new Date()]; const carsByMake: string[][] = [ ['f150', 'f151'], ['corolla'], ]; // Help with inference with extracting values const car = carMakers[0]; const myCar = carMakers.pop(); carMakers.map((car: string) : string => { return car.toUpperCase(); }); |
Multiple Types in Arrays
1 2 3 4 |
// Flexible types const importantDates = [new Date(), '2030-10-10']; importantDates.push('2030-10-10'); importantDates.push(new Date()); |
When to use Arrays?
When we want to represent a collection of records which some arbitrary sort order.
of same type.
https://stackoverflow.com/questions/49047886/whats-difference-between-array-and-tuple/49047969
Tuple vs Arrays
Tuple – A tuple is a grouping of unnamed, ordered values. Each value in a tuple does not need to be the same type.
Array An array is mutable collection. They are very efficient to create, but must always be a single type.
We have a literal object like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
const drink = { color: 'brown', carbonated: true, sugar: 40 } // array of string | number | boolean const pepsi = ['brown', true, 40]; // But we have to memorize that 1st is the color, 2nd is boolean, 3rd is number // so we can't use array // we use tuple const pepsi: [string, boolean, number] = ['brown', true, 40]; // that way we get compile time checking // pepsi[0] = 40; would give compile time error |
type alias
1 2 3 4 5 |
type Drink = [string, boolean, number]; // create a tuple type const MountainDew: Drink = ['yellow', true, 20]; const sprite: Drink = ['clear', true, 40]; const tea: Drink = ['brown', false, 0]; |
But Why Tuples!?
Here’s why we don’t really use it too much.
1 |
const carSpecs: [number, number] = [400, 33543]; |
It does not describe what those numbers mean. It is not descriptive.
Let’s use object instead. It is much more descriptive because we are forced to put in a key.
1 2 3 4 |
const carStats = { horsepower: 400, weight: 3354 } |