We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Extra Properties

Most of the time, when you pass an object to a function in TypeScript, it's:

  • Okay to have more properties than those defined in the function's parameter type
  • Not okay to have missing properties

However, when you pass an object literal directly to a function, TypeScript performs what's called "excess property checking". Which means it also will not allow extra properties.

For example, say we have this type:

type Spaceship = {
  name: string;
  speed: number;
};

and we make an object with one extra property:

const falcon = {
  name: "Millennium Falcon",
  speed: 75,
  weapons: 4,
};

We can pass this object to a function that expects a Spaceship:

function pilot(ship: Spaceship) {
  console.log(`Piloting ${ship.name} at ${ship.speed} light-years per hour`);
}

// this is fine
pilot(falcon);

But interestingly, if we pass in the same object literal (no variable assignment), TypeScript will throw an error:

// Error: Object literal may only specify known properties, and 'weapons' does not exist in type 'Spaceship'.
pilot({ name: "Millennium Falcon", speed: 75, weapons: 4 });

It's also worth noting that many of these kinds of rules are configurable in the tsconfig.json file, which we'll cover later. We'll mostly refer to default behavior in this course.

Assignment

Support.ai management asked to be copied on all emails...