create an array in typescript

To create an array in TypeScript, you can use the array literal syntax or the Array constructor:

  1. Using array literal syntax:
index.ts
let myArray: number[] = [1, 2, 3, 4, 5];
let myStringArray: string[] = ["apple", "banana", "orange"];
let myMixedArray: any[] = [1, "apple", true];
148 chars
4 lines
  1. Using the Array constructor:
index.ts
let myArray: number[] = new Array<number>(1, 2, 3, 4, 5);
let myStringArray: string[] = new Array<string>("apple", "banana", "orange");
let myMixedArray: any[] = new Array<any>(1, "apple", true);
196 chars
4 lines

In the example above, myArray is an array of numbers, myStringArray is an array of strings, and myMixedArray is an array that can hold any type of data (number, string, boolean, etc.).

Note: TypeScript supports type annotations, but if you don't specify the type explicitly, TypeScript will infer the type based on the initial values of the array.

You can access and manipulate array elements using indexes, just like in JavaScript. For example:

index.ts
console.log(myArray[0]); // Output: 1
myArray[3] = 10;
console.log(myArray); // Output: [1, 2, 3, 10, 5]
105 chars
4 lines

Remember to use the appropriate type annotations to ensure type safety when working with arrays in TypeScript.

related categories

gistlibby LogSnag