Interfaces and Classes are used to create custom types in TypeScript. These are similar but also have significant differences which I want to mention below.
Difference between Interfaces and Classes
Interfaces | Classes |
---|---|
Define a new type | Define a new type |
Properties (signatures) | Properties (with implementation) |
Methods (signatures) | Methods (with implementation) |
Cannot be instantiated | Can be instantiated |
Create an Interface
interface
keyword is used to create an interface following the name of the interface.
interface Employee {
name: string;
title: string;
}
Here Employee
represents the interface name with 2 string properties 'name' and 'title'.
Let's look into a complex example
interface Manager extends Employee {
department: string;
numOfEmployees: number;
scheduleMeeting: (topic: string) => void;
}
Now this Manager
interface inherits all the properties of Employee
interface. So in other words Manager
interface has 4 properties i.e., name, title, department, and numOfEmployees.
As I mentioned above, interfaces don't have method implementations. So any object that inherits Manager
interface will define the scheduleMeeting
method according to it.
Implement an Interface
Any object that implements above mentioned Employee
interface must have 2 properties with string types.
let newEmployee1: Employee = {
name: 'Sarah',
title: 'Software Engineer',
}
Let's see another example
let newEmployee2: Employee = {
name: 'James',
title: 'Team Lead',
teamName: 'Alpha squad'
}
Now newEmployee2
have one additional property teamName
but it still inherits the Employee
interface because as long as an object has all the required properties of an interface can inherit/extends an interface.
This is also called a Structural Type System.
An optional member of the interface
We can also declare optional members of the interface just like we did in optional params in a function.
interface Person {
firstName: string;
lastName: string;
midName?: string;
}
While implementing an interface, we can skip optional members of an interface, and the compiler won't give any error.
Feel free to connect on Twitter
Top comments (0)