They have similar structure but they are used in different ways. The class allows you to create new objects to be used in your application. Where the interface tells the compiler how thing should be structured. Below you can see that you can add a value to the label property. You can not do this with the interface.
interface Something {
label: string;
}
class Something {
label: string = 'some string value';
}
In the example below the interface enforces the Something class to always need a property named label and the type needs to be a string. If you change the type or remove the property all together. The compiler will complain.
interface ISomething {
label: string;
}
class Something implements ISomething {
label: string = 'some string value';
}
In the example above I recommend using the convention of adding a capital I in front of your interface names to eliminate confusion between classes and interfaces.
In the next example we'll use an interface (IUser) to allow the serveral classes to be passed into the getUserDescription function without the compiler complaining. This is called Polymorphism. Our function doesn't care if it is a Teacher or a Student or any other class. All it cares about is that the structure being passed in matches the interface.
interface IUser {
firstName: string;
lastName: string;
type: string;
}
class Student {
firstName: string = null;
lastName: string = null;
type: string = 'student';
courses: Array<any> = [];
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
}
class Teacher implements IUser {
firstName: string = null;
lastName: string = null;
type: string = 'teacher';
classes: Array<any> = [];
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
}
const getUserDescription = (user: IUser): string => {
return `${user.firstName} ${user.lastName} is a ${user.type}`;
};
getUserDescription(new Teacher('Harry', 'Jones')); // Harry Jones is a teacher
getUserDescription(new Student('Joe', 'Cool')); // Joe Cool is a student
If you notice above Teacher implements IUser but Student does not. You normally you would have both done in the same way but I wanted to show that you can enforce the structure at the class level or not.
Checkout my article http://www.codebelt.com/typescript/typescript-classes-object-oriented-programming/ for more info.