乐闻世界logo
搜索文章和话题

How can you define an array with a specific type in TypeScript?

1个答案

1

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:

typescript
let 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:

typescript
numbers.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:

typescript
let 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:

typescript
numbers.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:

typescript
function 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.

2024年7月29日 13:58 回复

你的答案