1
votes

All:

I am pretty new to typescript, when I try typescript handbook, there are two type(function and class) Interface definitions:

For function, it says:

interface SearchFunc {
  (source: string, subString: string): boolean;
}

For class, it says:

interface ClockInterface {
    currentTime: Date;
    setTime(d: Date);
}

class Clock implements ClockInterface  {
    currentTime: Date;
    setTime(d: Date) {
        this.currentTime = d;
    }
    constructor(h: number, m: number) { }
}

What confuses me here is:

Why there are diff ways to define function inside Interface, in the Function Types section it says:

To describe a function type with an interface, we give the interface a call signature. This is like a function declaration with only the parameter list and return type given.

Why both works when define function? Or the second one( setTime(d: Date); part ) is not a function definition?

Thanks

1

1 Answers

0
votes

An interface is a contract that describes things the implementing entity must implement. You provide a function signature in a class interface as a way of saying: "If you are implementing this interface, then your class must contain this function and accept these arguments.

The other interface you showed is a whole interface just for a function. This way you can pass this function somewhere that accepts the SearchFunc interface. As long as your function implementing that interface accepts the same parameter types (doesn't need to be same variable names) then the requirements are satisfied.

For example:

interface SearchFunc {
  (source: string, subString: string): boolean;
}

function doStuff (searchUtility: SearchFunc) {
  var contentExists = searchUtility(textToSearch, 'query text');
}

Whatever you pass to doStuff needs to adhere to the SearchFunc interface argument types. doStuff is declaring a contract that says "If you give me a function, this is how it must look. It must accept a string of text to search, a string of text to query for, and it must return a boolean.

doStuff(function (srcText: string, queryText: string) {
  return srcText.indexOf(queryText) !== -1;
}); 

The logic in the function that actually does the searching isn't specified in the contract. Only what parameter types are accepted and what type the return value should be.


So basically a class interface lets you define how an entire class should look, including any methods on that class (methods are functions attached to objects). A function interface just acts as a type so that some other API could expect that type and you'd have to satisfy it. If all this hypothetical API is a function that looks a certain way then it would be overkill to make it depend on a whole class containing only one function definition.