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

Function type interfaces

We just saw how to define properties in interfaces. Similarly, we can also define function types in interfaces. We can define function types in interfaces by just giving the signature of the function with the return type. Note that, in the following code snippet, we have not added the function name:

interface AddCustomerFunc { 
  (firstName: string, lastName: string): string; 
} 

Now, we have AddCustomerFunc ready. Let's define an interface variable called AddCustomerFunc and assign a function of the same signature to it as follows:

var addCustomer: AddCustomerFunc; 
addCustomer = function(firstName: string, lastName: string) { 
  console.log('Full Name: ' + firstName + ' ' + lastName); 
  return firstName + ' ' + lastName; 
} 

The parameter name in the function signature can vary, but not the data type. For example, we can alter the fn and ln function parameters of the string type as follows:

addCustomer = function(fn: string, ln: string) { 
  console.log('Full Name: ' + fn + ' ' + ln); 
} 

So, if we change the data type of the parameter or the return type of the function here, the compiler will throw an error about the parameter not matching or the return type not matching with the AddCustomerFunc interface.

主站蜘蛛池模板: 宁明县| 苗栗市| 渑池县| 社旗县| 晋州市| 福泉市| 湘乡市| 科技| 巫山县| 临江市| 丰顺县| 深泽县| 通许县| 那曲县| 鄂伦春自治旗| 陆良县| 和龙市| 郓城县| 中宁县| 阿拉善左旗| 湖南省| 汉源县| 津南区| 安溪县| 石门县| 闻喜县| 禄丰县| 汽车| 龙里县| 吉水县| 界首市| 闵行区| 炎陵县| 江山市| 鹤岗市| 巍山| 红原县| 潍坊市| 辛集市| 常德市| 邹平县|