TypeScript Interfaces

TypeScript interfaces are a powerful way to define the structure of objects, ensuring that your code follows a specific contract. They help catch errors early by enforcing type checks, making your code more predictable and easier to maintain. Whether you're defining shapes for objects, functions, or classes, interfaces provide a clear blueprint for how data should be structured.

What are Interfaces in TypeScript?

An interface in TypeScript is a way to define a contract for the shape of an object. It specifies what properties and methods an object must have, along with their types. Unlike classes, interfaces don’t contain any implementation—they only describe what the structure should look like.

For example, if you're working with user data, you can define an interface to ensure every user object has a name (string) and age (number). If an object doesn’t match this structure, TypeScript will flag it as an error, helping you catch mistakes before they cause issues in your code.

Declaring and Implementing Interfaces

Declaring an interface is simple—you use the interface keyword followed by the structure. Here’s how you can define and use one:

typescript
1
2
3
4
5
6
7
8
9
          interface User {
  name: string;
  age: number;
}

const newUser: User = {
  name: "Alice",
  age: 25,
};
        

If you try to assign an object missing name or age, TypeScript will show an error. Interfaces can also describe functions, classes, and even optional properties (using ?).

Extending Interfaces in TypeScript

Just like classes, interfaces can extend one another to build more complex types. This allows you to reuse existing interfaces while adding new properties.

typescript
1
2
3
4
5
6
7
8
9
10
11
12
          interface Person {
  name: string;
}

interface Employee extends Person {
  jobTitle: string;
}

const worker: Employee = {
  name: "Bob",
  jobTitle: "Developer",
};
        

By extending Person, the Employee interface inherits the name property while adding jobTitle. This keeps your code DRY (Don’t Repeat Yourself) and makes type definitions more flexible.