Skip to content

Object Types

Type objects inline or define their shape separately.

const car: { make: string; model: string; year: number } = {
  make: "Honda",
  model: "Civic",
  year: 2008,
};

TypeScript infers the type from the value:

const car = { make: "Ford" };
car.make = "Nissan"; // fine
car.make = 123; // Error: number isn't assignable to string

Use ? for properties that might not exist:

const car: { make: string; mileage?: number } = {
  make: "Honda",
  // mileage is optional, so this is valid
};

car.mileage = 50000; // can add it later

When you don’t know the property names ahead of time:

const scores: { [name: string]: number } = {};
scores.Matt = 95;
scores.Sarah = 88;
scores.Mike = "good"; // Error: string isn't assignable to number