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...