Get a Quote Right Now

Edit Template

Arrays

TypeScript is to be a static typechecker for JavaScript programs – in other words, a tool that runs before your code runs (static) and ensures that the types of the program are correct (typechecked).

Arrays: Arrays in TypeScript are similar to arrays in JavaScript, but with the added benefit of type annotations and type inference. To specify the type of an array like

[1, 2, 3], you can use the syntax number[];

Array Declaration: let numbers: number[] = [1, 2, 3, 4, 5];
let strings: string[] = ["apple", "banana", "cherry"];

Type Inference: TypeScript can often infer the type of the array based on the values you initialize it with, so you don’t always need to explicitly specify the type.
let inferredNumbers = [1, 2, 3, 4, 5]; // TypeScript infers type as number[]

Array Iteration: You can iterate through arrays using loops or methods like forEach, map, filter, etc.
let numbers: number[] = [1, 2, 3];
numbers.forEach(num => console.log(num));
let doubledNumbers = numbers.map(num => num * 2);


Array Type Union: You can create arrays that contain values of multiple types using type unions.
let mixed: (number | string)[] = [1, "two", 3, "four"];

Array Generics:
TypeScript also supports array generics to define arrays with a specific type parameter.
let arrayOfStrings: Array = ["hello", "world"];


Share

Leave a Reply

Your email address will not be published. Required fields are marked *