Interfaces

An interface is an abstract type that defines the behavior of a class. It provides a type definition for an object that can be exchanged between clients. This enables the client to only exchange an object that is compiled with the interface type definition; otherwise, we get a compile time error.

In TypeScript, interfaces define contracts of an object within your code and the code outside your project. Let's see how to use TypeScript with an example:

function addCustomer(customerObj: {name: string}) { 
console.log(customerObj.name);
}
let customer = {id: 101, name: "Rajesh Gunasundaram"};
addCustomer(customer);

The type-checker verifies the addCustomer method call and examines its parameter. The addCustomer expects an object with the name property of the string type. However, the client that calls addCustomer passed an object with two parameters: id and name, respectively.

However, the compiler ignores checking the id property as it is not available in the parameter type of the addCustomer method. What matters for the compiler is that the required properties are present.

Let's rewrite the method applying interface as a parameter type, as demonstrated:

interface Customer { 
name: string;
}
function addCustomer(customerObj: Customer) {
console.log(customerObj.name);
}
let customer = {id: 101, name: "Rajesh Gunasundaram"};
addCustomer(customer);

Here, we declared the Customer interface with the name parameter, and we modified the addCustomer signature to accept the parameter of the type Customer interface. The remaining statements are the same as the preceding code snippet. The compiler only checks for the shape of the object. It will not check whether the object we are passing implements the Customer interface. It only looks for the name property of the string type in the parameter and then allows it if present.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset