Defining arrays with specific types in TypeScript can be achieved through two primary methods: one using the syntax of a type followed by square brackets [], and the other using the generic array type Array<element type>.
1. Bracket Notation
When defining an array of type number, you can specify it as follows:
typescriptlet numbers: number[] = [1, 2, 3, 4];
This indicates that the variable numbers is an array where every element must be of type number. Attempting to add non-number values to this array will result in compilation errors.
For example, the following code will trigger an error:
typescriptnumbers.push("5"); // Error! String "5" is not of type number.
2. Generic Array Type
The generic array type Array<element type> provides equivalent functionality but uses a different syntax. Defining the same number array with a generic type is as follows:
typescriptlet numbers: Array<number> = [1, 2, 3, 4];
This also ensures all elements in the array are of type number. Similarly, adding elements of incompatible types will cause the TypeScript compiler to report errors:
typescriptnumbers.push("5"); // Error!
Example Application
Suppose you are developing a feature that requires storing and processing user age information. In this case, using a number array safely stores the data and facilitates operations like calculating the average age:
typescriptfunction calculateAverageAge(ages: number[]): number { const total = ages.reduce((acc, age) => acc + age, 0); return total / ages.length; } let userAges: number[] = [25, 32, 40, 29, 21]; let averageAge = calculateAverageAge(userAges); console.log(`Average Age is: ${averageAge}`); // Output the average age
Here, the array userAges of type number[] stores age data, and the function calculateAverageAge computes the average. This explicit declaration prevents errors such as inadvertently inserting non-numeric data while enhancing code readability and maintainability.