TypeScript Array Example

This post shows how to create an Array in TypeScript with an example.

Read the complete tutorial at https://www.javaguides.net/2019/09/typescript-array-tutorial-with-examples.html

TypeScript supports arrays, similar to JavaScript. There are two ways to declare an array:
  1. Using square brackets. This method is similar to how you would declare arrays in JavaScript.
//  Using square brackets
let programmingLangs : string[] = ['C', 'C++', 'Java', 'JavaScript'];
console.log(programmingLangs); // [ 'C', 'C++', 'Java', 'JavaScript' ]
  1. Using a generic array type, Array.
// Using a generic array type, Array<elementType>.
let programmingLangs: Array<string> = ['C', 'C++', 'Java', 'JavaScript'];
console.log(programmingLangs); // [ 'C', 'C++', 'Java', 'JavaScript' ]

Creating an Array Examples

Example: Array inline declaration and initialization

// array inline declaration and initialization
//  Using square brackets
let programmingLangs : string[] = ['C', 'C++', 'Java', 'JavaScript'];
console.log(programmingLangs);
// Using a generic array type, Array<elementType>.
let programmingLangs1: Array<string> = ['C', 'C++', 'Java', 'JavaScript'];
console.log(programmingLangs1);

Example: Array declaration and initialization in separate lines

let programmingLangs : string[];
programmingLangs = ['C', 'C++', 'Java', 'JavaScript'];

let programmingLangs: Array<string>;
programmingLangs = ['C', 'C++', 'Java', 'JavaScript'];

Reference



Comments