- An interface defines the syntax that an entity must have to follow.
- Interfaces are only at compile time.
- Interfaces contain only the declarations of the members.
- A deriving class must define the required members.
- It is also helpful in providing a structure.
Let me give you an example with users interface: i-users.ts
1
2
3
4
5
6
|
export interface IUsers {
userName: string;
userId: string;
userEmail: string;
phone?: number;
}
|
And now let say we have a users service and inside that, we have a function 'updateUser' to update the user info.
1
2
3
4
5
6
7
8
|
import {IUsers} from 'i-users'
----
---
public updateUser(id: string, userData: IUsers): Observable<IUsers> {
// make api call to update the user info
}
-----
-----
|
Here in the above code snippet, we are passing a parameter userData of type IUsers. This means we can not pass any other format except the IUsers.
But did you notice we have a question mark (?) at property phone and which means phone is optional.
So I can pass data something like:
1
2
3
4
5
|
let userData = {
userName: 'Saurabh',
userId: '545154',
userEmail: 'info@www.coding4developers.com'
}
|
Here above userData is valid data to pass the API.
Now let's have another example of invalid parameters:
1
2
3
4
5
6
|
let userData = {
userName: 'Saurabh',
userId: '545154',
userEmail: 'info@www.coding4developers.com',
city: 'Noida'
}
|
Here this is invalid data because we have not declared the city in our interface and that's why this will result in an error at compile time.
Interfaces are also helpful when sometime we forgot to pass a required parameter and this will help you at the compile time by telling that a particular member is not defined.