Skip to content

Array Types

von Schappler edited this page Oct 19, 2024 · 1 revision

Creating Array types

When dealing with with array types in TypeScript, it ususally infers the the type in which the array will be constructed with, when the array is declared AND initialized.

Though, the best practices suggest that we declare those manually, as it'll be detailed below.

To define array types formed by any pre-defined type, the syntax pretty straight: it consist on adding a pair of opening and closing square bracket to the type of the variable...

type Grades = number[];

type Student = {
  name: string;
  age: number;
  grades: Grades;
};

type Classroom = Student[];

const grades1: Grades = [10, 9, 10, 5];
const grades2: Grades = [10, 8, 8, 4];

const student1: Student = {
  name: 'S1',
  age: 10,
  grades: grades1,
};

const student2: Student = {
  name: 'S2',
  age: 9,
  grades: grades2,
};

const class1: Classroom = [student1, student2];
Clone this wiki locally