Post

Typescript Pt. 3 - Arrays with TypeScript

Creating arrays

We can create arrays in two ways:

1
2
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];

Creating 2D arrays

1
2
3
4
5
let matrix: number[][] = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

Creating arrays with a fixed length

1
let list: number[] = new Array(5);

Creating arrays with a fixed length and initial values

1
let list: number[] = new Array(5).fill(0);

Creating an array from custom types

1
2
3
4
5
6
7
8
type Person = {
  name: string;
  age: number;
};

const people: Person[] = [];
people.push({ name: "John", age: 42 });
people.push({ name: "Jane", age: 32 });

Passing arrays as function parameters

1
2
3
4
5
function sum(numbers: number[]): number {
  return numbers.reduce((a, b) => a + b, 0);
}
// sum([1, 2, 3]) === 6
// the above function sums all the numbers in an array
This post is licensed under CC BY 4.0 by the author.