- In TypeScript, you can declare an array type using the syntax type[] or Array<type>, where type is the type of the elements in the array.
Here are a few examples:
// Array of numbers
let numbers: number[] = [1, 2, 3, 4, 5];
let moreNumbers: Array<number> = [6, 7, 8, 9, 10];
// Array of strings
let strings: string[] = ["apple", "banana", "cherry"];
let moreStrings: Array<string> = ["date", "elderberry", "fig"];
// Array of booleans
let booleans: boolean[] = [true, false, true];
let moreBooleans: Array<boolean> = [false, true, false];
// Array of any
let anyValue: any[] = [1, "2", true, [3, "2"], { name: "john" }]
let moreAnyValue: Array<any> = [1, "2", true, [3, "2"], { name: "john" }]
- You can also use type assertions to specify the type of an array without initializing it:
let emptyArray: number[] = [];
emptyArray.push(1);
emptyArray.push(2);
emptyArray.push(3);
// Type assertion
let stringArray: string[] = [] as string[];
stringArray.push("hello");
stringArray.push("world");
console.log(emptyArray);
console.log(stringArray);
[ 1, 2, 3 ]
[ 'hello', 'world' ]
- TypeScript also supports readonly arrays, which are arrays whose elements cannot be modified once they are assigned:
let readonlyArray: readonly number[] = [1, 2, 3];
readonlyArray[0] = 4; // Error: Index signature in type 'readonly number[]' only permits reading
readonlyArray.push(4); // Error: Property 'push' does not exist on type 'readonly number[]'
- In addition to these basic array types, TypeScript provides various utility types and methods to work with arrays, such as Partial<T>, ReadonlyArray<T>, map(), filter(), etc. These utilities can be helpful when working with arrays in TypeScript.
No comments:
Post a Comment