DEV Community

Cover image for The differences between type and interface in TypeScript.
Caio
Caio

Posted on

2 1

The differences between type and interface in TypeScript.

What is type? In TypeScript, type is a way to define a custom type. It can be used to create complex types from primitive types or other types. With type, you can define types for objects, unions, intersections, and even more complex types. Example:

// Defining a type for an object
type Person = {
  name: string;
  age: number;
};

// Using the type
const person: Person = {
  name: "João",
  age: 25,
};
Enter fullscreen mode Exit fullscreen mode

When to use type? Unions and Intersections: When you need to combine types, type is a good choice. It allows you to create unions (one type or another) and intersections (combination of types).

type ID = string | number; // Union
type Coordinates = { x: number } & { y: number }; // Intersection
Enter fullscreen mode Exit fullscreen mode

Developer tip: If you need to define types that are not just objects, like unions of primitive types, type is more flexible.

What is interface? Interface is another way to define the shape of an object in TypeScript. It is mainly used to define contracts for objects, meaning it specifies which properties and methods an object must have. A class/object that implements an interface must have all the fields and methods (except those explicitly marked as optional). Therefore, interfaces are used for type-checking.

Example:

// Defining an interface for an object
interface Car {
  brand: string;
  year: number;
}

// Using the interface
const car: Car = {
  brand: "Toyota",
  year: 2020,
};


Enter fullscreen mode Exit fullscreen mode

Key Differences

1- Extension: interface can be extended by other interfaces, while type can use intersections to combine types, but cannot be extended in the same way.

2- Unions: type can create unions of types, whereas interface cannot.

3- Class Implementation: interface is more commonly used to define contracts that classes should follow.

For more informations:

If you want to dive deeper, I recommend exploring the official TypeScript documentation, where you'll find a playground with examples and detailed explanations about type and interface."

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE