Objects and Interfaces

Describe the shape of your data

9 min read

Objects have shapes

In JavaScript, objects carry most of your interesting data: a user, a product, a blog post. TypeScript lets you describe an object's shape, meaning which properties it has and what type each one is:

let user: { name: string; age: number } = {
  name: 'Gwen',
  age: 28
};

That works, but imagine writing { name: string; age: number } in every function that touches a user. It gets long, and if the shape ever changes you have to update it everywhere. There is a better way.

Interfaces give shapes a name

An interface lets you define a shape once and refer to it by name everywhere:

interface User {
  name: string;
  age: number;
  email: string;
}

const gwen: User = {
  name: 'Gwen',
  age: 28,
  email: 'gwen@example.com'
};

Now User is a reusable label for that whole shape. Functions become short and readable:

function sendWelcome(user: User): void {
  console.log('Welcome, ' + user.name + '!');
}

sendWelcome(gwen);

What the checker catches

With the interface in place, TypeScript verifies every object you claim is a User. All of these produce errors:

const a: User = { name: 'Sam', age: 30 };
const b: User = { name: 'Sam', age: '30', email: 's@x.com' };

The first is missing email. The second has age as a string instead of a number. And if you later typo a property name, like user.emial, TypeScript catches that too, because emial is not part of the shape.

Interfaces are documentation that cannot go stale

Think of an interface as a contract between the parts of your website. The signup form, the profile page, and the email sender can all agree on what a User looks like. If the shape changes, say you rename email to emailAddress, TypeScript instantly lists every file that needs updating. Written docs drift out of date; interfaces cannot, because the checker enforces them on every build.

Naming habit: interfaces are usually named with a capital first letter, like User, Product, or BlogPost. It is a convention, not a rule, but nearly all TypeScript code follows it.

Quick check

Q1 What is the main benefit of defining an interface for an object shape?

Q2 An interface User requires name, age, and email. What happens if you assign an object without email to a User variable?

Want to save your progress? It's free.

Create a free account