theory.ts

Objects & Interfaces

Defining Objects in TypeScript

Objects in TypeScript are collections of key-value pairs with explicitly defined structures using type annotations.

  • Objects must conform to the defined structure, ensuring all required properties are present.
  • Additional properties not specified in the type definition will result in an error.
  • TypeScript enforces correctness at compile time, reducing runtime errors.
// Object with explicit type annotation
let person: { name: string; age: number } = {
  name: "Jake",
  age: 25
};

// Missing or extra properties cause errors
let invalidPerson = { name: "Jake" }; // Error: Property 'age' is missing
let extraProperty = { name: "Jake", age: 25, city: "Sydney" }; // Error: Extra property 'city'