What’s the difference between interface and class in Typescript?
Interface: The interface is only responsible for declaring the type of member variables, but does not do the specific implementation.
Class: Class both declares and implements member variable types.
What is interface?
An important concept in OOP languages is Interfaces, which are abstractions of behavior that need to be implemented by classes.
Interfaces in TypeScript are a very flexible concept. In addition to abstracting part of the behavior of a class, they are often used to describe the Shape of an object.
Such as:
interface Person {
name: string;
age: number;
}
Copy the code
The above example is the simplest interface, with two properties called name and age, whose values are a string and a number. Typescript throws an error when you don’t follow the convention of using interfaces to constrain the content of incoming variables.
What is Class?
In the traditional method, JavaScript implements the concept of class through the constructor and realizes inheritance through the prototype chain. In ES6, class is finally here. In addition to implementing all the functionality of ES6 classes, TypeScript adds a few new uses. (Today, we only talk about classes and interfaces, but other features of specific classes can refer to the official)
/ / class Person
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age; }};// The class acts as an interface containing only its instance properties and instance methods (constructor and static are not included).
const person: Person = {
name: 'Joe',
age: 18
};
// Interfaces inherit classes
interface Person1 extends Person{
sex: string,
printName() : void
};
const person1: Person1 = {
name: 'Joe',
age: 18,
sex: 'male',
printName() {
console.log(this.name)
}
};
// The class implements the interface
class Person2 implements Person1 {
name: string;
age: number;
sex: string;
email: string;
printName() {
console.log(this.name)
};
}
Copy the code
conclusion
Declaring a class in Typescript actually creates an interface with the same name in addition to a class (which contains only instance properties and instance methods). So classes can be used either as classes or as interfaces.
Personal blog address, interested can take a look