TypeScript Arrays
TypeScript has a specific syntax for typing arrays.
19th August 2022
Time to read: 1 min
TypeScript supports arrays, similar to JavaScript. There are two ways to declare an array:
- Using square brackets.
let fruits: string[] = ['Apple', 'Orange', 'Banana'];
- Using a generic array type.
let fruits: Array<string> = ['Apple', 'Orange', 'Banana'];
Arrays can be declared and initialized separately.
let fruits: Array<string> = [];
// or let fruits:string[] = [];
fruits = ['Apple', 'Orange', 'Banana'];
let ids: Array<number> = [];
// or let ids:number[] = [];
ids = [23, 34, 100, 124, 44];
let values: Array<boolean> = [];
// or let values:boolean[] = [];
values = [true, true, false, true, true];
String Array
const names: string[] = [];
names.push("Dylan"); // no error
// names.push(3); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.
Number Array
const ids: number[] = [];
ids.push(3); // no error
// ids.push("Dylan"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
Boolean Array
const arr: boolean[] = [];
arr.push(false); // no error
// arr.push("Dylan"); // Error: Argument of type 'string' is not assignable to parameter of type 'boolean'.
Multi Type Array
An array in TypeScript can contain elements of different data types using a generic array type syntax.
let values: (string | number)[] = ['Apple', 2, 'Orange', 3, 4, 'Banana'];
// or
let values: Array<string | number> = ['Apple', 2, 'Orange', 3, 4, 'Banana'];
Initialize a multi-type array
let mixedTypes: Array<string | number | boolean> = []
// or let mixedTypes: Array<any> = []
// let mixedTypes:any[] = []
mixedTypes.push('apple')
mixedTypes.push(true)
mixedTypes.push(6)
Readonly
The readonly
keyword can prevent arrays from being changed.
const names: readonly string[] = ["Dylan"];
names.push("Jack"); // Error: Property 'push' does not exist on type 'readonly string[]'.
Type Inference
TypeScript can infer the type of an array if it has values.
const numbers = [1, 2, 3]; // inferred to type number[]
numbers.push(4); // no error
numbers.push("2"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
let head: number = numbers[0]; // no error