liveBook · Manning

Array type

As explained in Essential TypeScript 5, Third Edition

An array type is a TypeScript type that specifies the element type or allowable element types of an array.

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

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Explains bracket notation, union-element syntax, callback typing, and inference failures through focused code examples.
Examples
Uses typed prices and names, forEach tax calculation, mixed numeric and string values, and objects with inconsistent shapes.
What it assumes
Assumes familiarity with JavaScript arrays and teaches how TypeScript restricts their element types.
What you can do after
Apply it via TypeScript annotations to constrain array contents and catch invalid element operations during compilation.
How it connects
Connects array types to type annotations, union types, type inference, object shapes, and forEach callbacks.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.