Array type in TypeScript are defined using <Type>[]
where type stands for the data array is going to hold, it can be primitive or non-primitive.
JavaScript Arrays are ordered list of data which can hold different types in same array. Below initialization is a valid case in JavaScript.
// JavaScript Array declaration and initialization
let valuesArray = [ 1, 2.5, 'a' , false ]
But in TypeScript Arrays once defined it will only hold the specified type of data, this helps to avoid run time errors during array processing.
Array Declaration for Single Type
// Syntax for Array declaration for single type
let nameOfArray : type [ ] ;
// TypeScript array declaration and initialization
let integerArray : number [] = [1, 2, 3 ]
let alphabetArray : string [] = [ 'a', 'b' , 'c' ]
Array Declaration for Multiple Type
In TypeScript, we can define arrays that can hold multiple type of data, meaning that apart from holding one type of value in array we can hold different types as well. This is achieved by separating the types using pipe "|"
symbol.
// Syntax for Array declaration for multiple types
let nameOfArray : (type A | type B ) : [] ;
let
Summary
- Syntax to declare an array is
let arrayName : type [ ]
- Array can hold mixed type as well using pipe
"|"
symbol. Syntaxlet arrayName : (typeA: typeb ) [ ]