CodeBlanks Logo Icon CodeBlanks

Array type

Learn to define arrays and specify their types.

Array type

In TypeScript, an array is an ordered list of values of the same type. The array type is written in two ways: number[] or Array<number>. The type inside the brackets specifies the type of elements the array holds. The type annotation comes after the variable with :.

let sayilar: number[] = [1, 2, 3];
let isimler: Array<string> = ["Ali", "Ayşe"];

Type checking and inference

When you specify a type for an array, TypeScript prevents adding wrong-typed elements. Even without a type annotation, TypeScript infers the array type from the initial assignment. Writing the explicit type is safer.

let renkler: string[] = ["kırmızı", "mavi"];
renkler.push("yeşil");
// renkler.push(5); // Error

Practice Prices array

Define a number[] array named fiyatlar with the values 100, 250, 75. Then print the array with console.log.

Starter code

index.ts
// fiyatlar dizisini number[] türüyle tanımla ve yazdır

Sample solution

index.ts
let fiyatlar: number[] = [100, 250, 75];
console.log(fiyatlar);

Expected output

[ 100, 250, 75 ]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the `Array<number>` notation specify?

  • All elements of the array being of number type Correct answer
  • Elements of the array being of different types
  • The array holding only a single number
  • The array always starting empty

Explanation: The `Array<number>` notation requires every element of the array to be of type `number`; adding a different type gives a compile error.

2 Specify an array type

Question
let notlar: number____ = [70, 85, 90];
Answer
let notlar: number[] = [70, 85, 90];

Explanation: The `number[]` notation specifies an array type of `number` elements; so two square brackets are needed in the blank.

3 Array type notations

Term Meaning
number[] Short notation for a number array
Array<string> General notation for a string array
boolean[] Short notation for a boolean array
Array<number> General notation for a number array

All lessons in Beginner