An array type specifies the element type an array may contain while preserving JavaScript's flexible length. Write the element type followed by square brackets, such as number[] or string[]. section 9.2
Listing 9.4 Using arrays in the index.ts file in the src folder
function calculateTax(amount: number): number {
return amount * 1.2;
}
function writePrice(product: string, price: number): void {
console.log(`Price for ${product}: $${price.toFixed(2)}`);
}
let prices: number[] = [100, 75, 42];
let names: string[] = ["Hat", "Gloves", "Umbrella"];
writePrice(names[0], calculateTax(prices[0]));
writePrice(names[1], calculateTax(prices[1]));
writePrice(names[2], calculateTax(prices[2]));
A complete src/index.ts example keeps prices and product names in separately typed arrays, then passes their indexed values to typed functions. section 9.2
Use array annotations to make element operations predictable:
- number[] allows number operations, while string[] allows string operations; forEach callbacks receive the corresponding element type. section 9.2
- For multiple permitted element types, parenthesize the union before the brackets: (number | string)[]. section 9.2
- When the annotation is omitted, TypeScript infers an array type from its initial values. Adding a string to numeric values produces (string | number)[] and can break numeric callbacks. section 9.2.2
Arrays of objects
TypeScript also derives an array's type from object shapes. If an array combines { name: string; price: number } objects with an object containing only name, the safe common shape becomes { name: string }[], so reading prod.price fails. section 10.2
