官术网_书友最值得收藏!

  • Expert Angular
  • Mathieu Nayrolles Rajesh Gunasundaram Sridhar Rao
  • 300字
  • 2021-07-15 17:05:31

Interfaces

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

In TypeScript, interfaces define contracts for 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); 
} 
  
var customer = {id: 101, name: "Rajesh Gunasundaram"}; 
addCustomer(customer); 

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

However, the compiler does not check the id property as it is not available in the parameter type of the addCustomer method. It only matters for the compiler that the required properties are present.

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

interface Customer { 
  name: string; 
} 
  
function addCustomer(customerObj: Customer) { 
  console.log(customerObj.name); 
} 
var 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 same as in the previous code snippet. The compiler only checks for the shape of the object as TypeScript implements the structural type system. 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 it's present.

主站蜘蛛池模板: 太仓市| 泉州市| 阿拉善盟| 胶南市| 南城县| 天津市| 苍梧县| 合肥市| 阿图什市| 桂阳县| 兴化市| 西丰县| 青神县| 安国市| 琼海市| 涞源县| 苍山县| 法库县| 纳雍县| 台湾省| 长乐市| 武汉市| 宁津县| 上杭县| 朝阳区| 乌拉特后旗| 津市市| 梁山县| 灯塔市| 西乌珠穆沁旗| 邹城市| 防城港市| 钟祥市| 平陆县| 台东县| 开平市| 邛崃市| 江门市| 白山市| 岐山县| 阳春市|