DEV Community

Yuya Hirano
Yuya Hirano

Posted on • Edited on

Interface vs Type in TypeScript

TypeScript, the statically typed superset of JavaScript, provides developers with various ways to define the shape of data. Two of the most commonly used options are interface and type.

Interface in TypeScript allow you to define a blueprint for objects. They are used to specify the structure of objects that have a set of named properties, with specific types and optional values. For example:

interface User {
  name: string;
  age: number;
  isAdmin?: boolean;
}

const user: User = {
  name: "John Doe",
  age: 30
};
Enter fullscreen mode Exit fullscreen mode

Type, on the other hand, can be used to describe any type in TypeScript, including primitives, objects, and even functions. The syntax for defining a type is similar to an interface, but it uses the type keyword instead:

type UserType = {
  name: string;
  age: number;
  isAdmin?: boolean;
};

const user: UserType = {
  name: "John Doe",
  age: 30
};
Enter fullscreen mode Exit fullscreen mode

The main difference between interface and type is that interface can be extended and merged, while type cannot. For example, you can create a new interface that extends an existing interface:

interface AdminUser extends User {
  role: string;
}

const adminUser: AdminUser = {
  name: "Jane Doe",
  age: 35,
  role: "Administrator"
};
Enter fullscreen mode Exit fullscreen mode

In conclusion, both interface and type serve the purpose of defining the shape of data in TypeScript. However, the choice between the two depends on the specific use case. If you want to create a blueprint for objects and extend it, use interface. If you want to describe any type in TypeScript, use type.

Top comments (0)