Typescript array
Created By: chatGPT
In TypeScript, an array is a special data structure that can hold multiple values. You can create an array using brackets
[]
and separate elements with commas. Arrays can hold values of a specific type, which enhances type safety.let numbers: number[] = [1, 2, 3, 4, 5];
let fruits: string[] = ['apple', 'banana', 'orange'];
You can also use the Array generic type to create arrays. This is especially useful when you need to work with more complex types.
let mixedArray: Array<string | number> = [1, 'apple', 2, 'banana'];
To access elements in an array, use their index. Remember that TypeScript uses zero-based indexing, meaning the first element is at index 0.
console.log(numbers[0]); // Outputs: 1
console.log(fruits[1]); // Outputs: banana
You can also use array methods to manipulate arrays. Here are some common methods:
// Adding an element to the end of the array
numbers.push(6);
// Removing the last element
numbers.pop();
// Iterating over an array
fruits.forEach(fruit => {
console.log(fruit);
});
To define an array with mixed types (objects, strings, etc.), you can use a tuple. This is a way to define a fixed-length array with known types at each index.
let tuple: [string, number] = ['apple', 5];
In TypeScript, Type Inference allows you to define an array without specifying its type explicitly, as long as the context is clear. TypeScript will automatically infer the type based on the provided values.
let inferredArray = [true, false, true]; // inferred as boolean[]
You can also utilize the spread operator for copying arrays or merging them.
let newArray = [...fruits, ...numbers];
Handling arrays in TypeScript provides better robustness due to its static typing system, making it easier to catch errors during development.
let arrayAlwaysNumber: number[] = [1, 2, 'three']; // Error: Type 'string' is not assignable to type 'number'