TypeScript Interfaces | Why use interfaces in angular typescript

  • 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

And now let say we have a users service and inside that, we have a function 'updateUser' 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:

Here above userData is valid data to pass the API.
Now let's have another example of invalid parameters:

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.

Share This:

Leave a Reply

Your email address will not be published. Required fields are marked *