← Back to all tutorials

Objects & Arrays

Working with typed arrays and objects in TypeScript.

Objects & Arrays

Arrays

Arrays in TypeScript are typed — once created with a type, only that type can be added:

let names: string[] = ["Mario", "Luigi", "Peach"];
names.push("Toad");   // ✅ OK
names.push(3);        // ❌ Error!

let ages: number[] = [25, 30, 28];
let mixed: (string | number)[] = ["Ken", 4, "Ryu", 7];

Objects

Object properties are typed based on their initial values:

let ninja = {
    name: "Mario",
    belt: "black",
    age: 30,
};

ninja.name = "Luigi";   // ✅ OK
ninja.age = "thirty";   // ❌ Error — must be number
ninja.skills = ["fight"]; // ❌ Error — property doesn't exist

Object Structure

Once an object is defined, its structure is fixed:

ninja = {
    name: "Yoshi",
    belt: "green",
    age: 25,
};  // ✅ OK — same structure

ninja = {
    name: "Yoshi",
    belt: "green",
};  // ❌ Error — missing 'age' property

Key Takeaways

  • Arrays are typed: string[], number[]
  • Mixed arrays use union types: (string | number)[]
  • Object property types are inferred from initial values
  • Object structure (shape) can't be changed after creation