TypeScript Array Type
In TypeScript, array types are used to store multiple values of the same type. Declaring the element type of an array improves both safety and readability.
Basic Array Type Declaration
let numbers: number[] = [1, 2, 3, 4];
let fruits: string[] = ["apple", "banana", "orange"];
Declarations like `number[]` and `string[]` ensure that the array contains only elements of that type. Adding a different type of value will cause a compile-time error.
Using Generic Array Syntax
let bools: Array<boolean> = [true, false, true];
The `Array< type >` syntax can also be used to define arrays. This form is especially preferred when working with complex types.
Union Types in Arrays
let mixed: (string | number)[] = ["text", 42, "more text", 99];
With union types, arrays can hold elements of more than one type. For example, a `mixed` array can include both `string` and `number` values.
Arrays of Objects
type User = {
id: number;
username: string;
};
let users: User[] = [
{ id: 1, username: "alice" },
{ id: 2, username: "bob" },
];
Arrays can also store objects with specific structures. For example, a `users` array can contain objects of type `User`, where each object has well-defined properties.
Readonly Arrays
const fixedNumbers: readonly number[] = [1, 2, 3];
// fixedNumbers.push(4); // Hata!
Arrays declared with the `readonly` keyword cannot be modified. This ensures type safety when working with immutable data.
Type Safety in Array Functions
const names: string[] = ["Alice", "Bob", "Charlie"];
const upperNames = names.map((name) => name.toUpperCase());
Operations like `map` and `filter` on arrays also benefit from type safety. TypeScript automatically infers the correct return types.
Preventing Type Errors in Arrays
Thanks to TypeScript's array type system, type mismatches and invalid operations on arrays can be caught during compile time, improving overall code stability.
Back