Arrays in TypeScript

In TypeScript, an array is a numbered sequence of elements. Arrays in TypeScript are more flexible than in some other languages, as they can be resized dynamically.

// Here we create an array `a` that will hold 5 numbers.
// By default, an array is initialized with `undefined` values.
let a: number[] = new Array(5);
console.log("emp:", a);

// We can set a value at an index using the
// array[index] = value syntax, and get a value with
// array[index].
a[4] = 100;
console.log("set:", a);
console.log("get:", a[4]);

// The length property returns the length of an array.
console.log("len:", a.length);

// Use this syntax to declare and initialize an array
// in one line.
let b: number[] = [1, 2, 3, 4, 5];
console.log("dcl:", b);

// In TypeScript, you can use the spread operator (...)
// to create a new array with the same elements.
b = [...b];
console.log("spread:", b);

// TypeScript doesn't have a direct equivalent to Go's
// index-based initialization, but you can achieve
// similar results using Array.from()
b = Array.from({length: 5}, (_, i) => i === 0 ? 100 : i === 3 ? 400 : i === 4 ? 500 : 0);
console.log("idx:", b);

// Array types are one-dimensional, but you can
// create multi-dimensional arrays.
let twoD: number[][] = [];
for (let i = 0; i < 2; i++) {
    twoD[i] = [];
    for (let j = 0; j < 3; j++) {
        twoD[i][j] = i + j;
    }
}
console.log("2d: ", twoD);

// You can create and initialize multi-dimensional
// arrays at once too.
twoD = [
    [1, 2, 3],
    [1, 2, 3],
];
console.log("2d: ", twoD);

Note that arrays appear in the form [v1, v2, v3, ...] when printed with console.log.

When you run this TypeScript code, you should see output similar to this:

emp: [ <5 empty items> ]
set: [ <4 empty items>, 100 ]
get: 100
len: 5
dcl: [ 1, 2, 3, 4, 5 ]
spread: [ 1, 2, 3, 4, 5 ]
idx: [ 100, 0, 0, 400, 500 ]
2d:  [ [ 0, 1, 2 ], [ 1, 2, 3 ] ]
2d:  [ [ 1, 2, 3 ], [ 1, 2, 3 ] ]

This example demonstrates how to work with arrays in TypeScript, including creation, initialization, accessing elements, and working with multi-dimensional arrays. TypeScript provides more flexibility with arrays compared to some other languages, allowing for dynamic sizing and offering convenient methods for array manipulation.