TypeScript Arrays
In TypeScript, arrays are considered to be collections of values that share a single, generic type. All elements must conform to the types specified in the array definition (e.g., string[]), or a union type if multiple element types are allowed (e.g., (string | number)[]).
Defining an array
Array types can be inferred during the initialization of a new array.
In this example, the vowels array is inferred to consist of elements of type string:
const vowels = ['a', 'e', 'i', 'o', 'u'];vowels.push('y'); // Okvowels.push(7);// Error: Argument of type 'number' is not assignable to parameter of type 'string'.
Arrays can also be defined with the “generic” type of its elements already preset in two ways:
const vowels: string[] = ['a', 'e', 'i', 'o', 'u'];// alternate way using Array classconst altVowels: Array<string> = ['a', 'e', 'i', 'o', 'u'];
More than one type can be prescribed in the array definition with the “or” | operator:
const numbers: (string | number)[] = [1, '2', 3, 'four'];// Alternative syntax// const numbers: Array<string | number> = [1, '2', 3, 'four'];
As long as each element in numbers is of type string or number, it is valid.
Array Types
An array type consists of the type of values inside the array followed by square brackets [].
Arrays without any initial contents may be declared as that type to tell TypeScript what will later go into them.
In this example, dates doesn’t initially include a value, so declaring it as Date[] tells TypeScript what’s allowed in it:
const dates: Date[] = [];dates.push(new Date('2021-12-1994')); // Okdates.push(10241995);// Error: Argument of type 'number' is not assignable to parameter of type 'Date'.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn TypeScript on Codecademy
- A full-stack engineer can get a project done from start to finish, back-end to front-end.
- Includes 51 Courses
- With Professional Certification
- Beginner Friendly.150 hours
- Learn TypeScript, a superset of JavaScript that adds types to make the language scale!
- Intermediate.10 hours