What are the differences between types and interfaces in TypeScript
Problem:
You start to use typescript to help in the development and to save time. But You are getting confused while using types and interfaces. And not getting the full benefit of TypeScript. Because you are not following the best practice.
So in this article, we are going to learn what are the differences between types and interfaces in TypeScript.
Solution:
In the previous version of TypeScript, the difference between types and interface was very much. But in the latest version types and interfaces becoming more similar. Here are some of the differences between them:
1. Let's say we have two interfaces with similar names with different properties
interface Book {
authorName: string;
};
interface Book {
bookName: string;
};
const book: Book = {
authorName: "George R. R. Martin",
bookName: "Song of Ice and Fire"
};
Both interfaces will be merged automatically into one interface. So if we use the Book interface, we will get a booth of the properties.
This does not happen with types. If we try to create types with the same name with different properties. TypeScript will throw an error.
2. We can easily extend and implement interfaces. For example, we have a class called Book and an interface called Newbook, using an interface we can easily extend this class.
class Book {
printBook = () => {
console.log("this is my Book");
};
}
interface NewBook extends Book {
name: string;
}
class NewestBook implements NewBook {
name: "Book";
constructor(authorName: string) {
this.name = name;
}
printBook = () => {
console.log("this is my Book");
};
}
But this extends and implementation is not possible with types.
3. We can combine multiple types into one type. This is called an intersection. By using & the keyword we can create an intersection type.
type BookName = {
name: “string”
};
type BookPage = {
age: number
};
type Book = BookName & BookPage;
We can also create a new intersection type by combining two interfaces. But if we combine two types we will not create an interface, because it does not work.
interface BookName {
name: “string”
};
interface BookPage {
age: number
};
type Book = BookName & BookPage;
4. We can create a new type by combing two or more types. This is called a union type. By using | the keyword we can create an intersection type.
type BookName = {
name: “string”
};
type BookPage = {
age: number
};
type Book = BookName | BookPage;
We can also create a new union type by combining two interfaces. But if we combine two types we will not create an interface, because it does not work.
interface BookName {
name: “string”
};
interface BookPage {
age: number
};
type Book = BookName | BookPage;
These are the few differences between types and interfaces. Hope you understand and can apply both in your project correctly.