An Insight Into Typescript Interface
Posted By : Vinay Tiwari | 21-Sep-2017
In this blog, we are going to be learn about interfaces. Now Interfaces are the most flexible way of describing types and typescript and because the type information is erased from a typescript program and we need compile it. We don't have to worry about the runtime overhead we are going to add when using interface. So, let's have a look on the syntax , to define any interface we used the keyword called as "interface.
For example :- We will create an interface of a person, i.e:
interface Person{ fname: string; lname: string; age: number; }
The person is going to have a "firstname" of type string and "lastname" of type string as well "age" of type number.
Now i have created a variable , i.e let employee1, this "employee1" is going to be of type person.
let employee1: Person{ fname: "params", lname: "anurag", age: 30, }
So, from this interface i can create firstname and this will be in "params" which is in string format and lastname and age which is also in string format.
Now lets remove the age 30. This will show error because property age is missing it must be present in the employee1 variable.
To eliminate this problem i have used optional method in interface.
interface Person{ fname: string; lname: string; age?: number; }
to remove this error we want to make a property optional which we we have to add in front of the params given as questionmark(?). So, now this property age is optional , and in interface employee1 firtsname and lastname will be valid.
Decalaration:-
So the only purpose of using interface and typescript is to describe particular type and can specify properties and these are going to be mandatory when we used the particular interface type and if we add a questionmark next to any property, then that particular property will be an optional.
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Vinay Tiwari
Vinay is a bright UI developer, having knowledge of HTML, CSS, Bootstrap, Jquery and AngularJs. His hobbies are interacting with people, listening music etc.