TypeScript Interfaces - TypeScript

What is TypeScript - Interfaces?

An interface is defined as the syntax that any entity must stick to.

Interface comprises of members which are properties, events and methods. The deriving class which uses the Interface should define the members.

Let us consider an object as below−

If we examine the signature of the object, it could be −

Whatever we want to reuse across objects, we define it by an interface.

Declaring Interfaces

The keyword interface is used in declaring an interface. Below is the syntax for it -

Syntax

Example: Interface and Objects

An interface is defined above with firstname, lastName and a method. Customer object makes use of the interface and define all properties as mentioned.

Another object with following signature, is still considered as IPerson because that object is treated by its size or signature.

Upon compiling, it will produce the following JavaScript code.

The result of the above example code is as below −

Interfaces are not impacted by JavaScript runtime as those are not converted to JavaScript. They are part of TypeScript. See the image below of TS Playground tool there is no java script produced when you declare an interface unlike a class.

 Interface and Objects

Union Type and Interface

Example below illustrates the use of Union Type and Interface −

Upon compiling, it will produce the following JavaScript code.

Its result is as below −

Interfaces and Arrays

Interface can be defined as both the kind of key an array uses and the type of entry it comprises of. Index can be of type number or type string.

Example

Interfaces and Inheritance

We can inherit an interface from other interface. TypeScript allows an interface to extend from multiple interfaces.

Inheritance can be implemented by using the extends keyword.

Syntax: Single Interface Inheritance

Syntax: Multiple Interface Inheritance

Example: Simple Interface Inheritance

Upon compiling, it will produce the following JavaScript code.

Its result is as below −

Example: Multiple Interface Inheritance

From the above code, the object Iobj is of the type interface leaf. The interface leaf has inherited has two attributes- v1 and v2 respectively. Hence, the object Iobj must now comprise of these attributes.

Upon compiling, it will produce the following JavaScript code.

The result of the above code is as below −

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

TypeScript Topics