An Interface is used to define a structure for an object. Basically, it is used to specify the properties and methods an object must implement.
interface Student {
id: number;
name: string;
}
let student: Student = {
id: 1,
name: "Bob",
};
In the above example, we declare an interface Student
with two properties id
and number
. Next, we create a variable student
which of type Student
and assign an id and name.
It is important to note that object student
must adhere to the interface definition. If we skip any property declared in the definition of the interface, Typescript will throw an error.
// NOT ALLOWED
let student: Student = {
// ERROR:: Property 'id' is missing in type '{ name: string; }' but required in type 'Student'.
name: "Bob",
};
This will throw an error, Property 'id' is missing in type '{ name: string; }' but required in type 'Student'.
An interface contains only the declaration of members and does not provide any implementation. For example, the below code is not allowed.
// NOT ALLOWED
interface Student {
id: number = 5; // An interface property cannot have an initializer.
name: string;
}
Implementing classes with Interface
We can also use an interface with a class to define the properties and methods the class must have. A class makes use of the implements
keyword to implement an interface.
To demonstrate it, let us declare an interface Animal
that can be used by the class Dog
.
interface Animal {
height: number;
weight: number;
speak(): void;
}
Interface Animal
has fields height
, weight
and a method speak()
. When declaring a class it must adhere to the above definition of the interface. Let’s go ahead and create a class Dog
.
class Dog implements Animal {
height: number;
weight: number;
constructor(height: number, weight: number) {
this.height = height;
this.weight = weight;
}
speak() {
console.log("woof woof");
}
}
let dog = new Dog(1, 2);
console.log(dog); // Dog {height: 1, weight: 2}
dog.speak(); // woof woof
As you can see, class Dog
contains both the fields(height, weight) and the speak()
method as mentioned in the interface.
If we try creating a class that does not include these properties, Typescript will throw an error.
// NOT ALLOWED
class Cat implements Animal {}
The above code will throw an error, Class 'Cat' incorrectly implements interface 'Animal'.Type 'Cat' is missing the following properties from type 'Animal': height, weight, speak