Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Function Interface

Why doesn't Typescript warn me that the function I am defining does not match the interface declaration, but it does warn me if I try to invoke the function.

interface IFormatter {     (data: string, toUpper : boolean): string; };  //Compiler does not flag error here. var upperCaseFormatter: IFormatter = function (data: string) {     return data.toUpperCase(); }    upperCaseFormatter("test"); //but does flag an error here. 
like image 625
MBeckius Avatar asked Feb 11 '13 14:02

MBeckius


People also ask

Can TypeScript interface have functions?

TypeScript Interface can be used to define a function type by ensuring a function signature. We use the optional property using a question mark before the property name colon. This optional property indicates that objects belonging to the Interface may or may not have to define these properties.

Can I define function in interface?

An interface is defined with the keyword interface and it can include properties and method declarations using a function or an arrow function.

How do you use interface methods in TypeScript?

Interfaces in TypeScript have two usage scenarios: you can create a contract that classes must follow, such as the members that those classes must implement, and you can also represent types in your application, just like the normal type declaration.

How do I inherit an interface in TypeScript?

Interfaces and Inheritance An interface can be extended by other interfaces. In other words, an interface can inherit from other interface. Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.


1 Answers

The interface ensures that all callers of functions that implement the interface supply the required arguments - data and toUpper.

Because TypeScript understands that JavaScript doesn't mind if you pass arguments that aren't used, it cleverly allows this in implementations.

Why is this okay? Because it means you can substitute any implementation of the interface without affecting calling code.

Example: You can substitute either IFormatter implementation and the code works.

interface IFormatter {     (data: string, toUpper: boolean): string; };  var upperCaseFormatter: IFormatter = function (data: string) {     return data.toUpperCase(); }  var variableCaseFormatter: IFormatter = function (data: string, toUpper: boolean) {     if (toUpper) {         return data.toUpperCase();     }      return data.toLowerCase(); }  // Switch between these at will //var formatter = upperCaseFormatter; var formatter = variableCaseFormatter;  formatter("test", true); 

If TypeScript didn't do this, your upperCaseFormatter would have to have to have a parameter called toUpper that wasn't used anywhere in the function - which makes the code less readable.

like image 63
Fenton Avatar answered Oct 02 '22 22:10

Fenton