TypeScript (TS) interfaces can describe function signatures. The thing implementing such an interface must be callable like a function, so it must be a function. A "callable interface", hard to imagine for an OO-thinking Java developer, actually exists in TS:
interface SearchFunction
{
(text: string, pattern: string): boolean;
}
const search: SearchFunction = function(text: string, pattern: string): boolean {
return text.search(pattern) >= 0;
}
const contained = search("ABCDEF", "EF");
console.assert(contained === true, "Pattern 'EF' is expected to be found in 'ABCDEF'");
The constant search
is typed to the interface SearchFunction
, and assigned to be a function that has the signature described in the interface. The subsequent test shows that this actually works.
The distinction between function and object (interface) is becoming quite diffuse here. Most likely this is another TS feature just to integrate already existing JavaScript APIs. From the TS language specification:
An object type containing one or more call signatures is said to be a function type.
Function types may be written using function type literals or by including call signatures in object type literals.
The TS Handbook speaks about "Hybrid Types". A TS interface can describe a mix of function and object, and if you also include index signatures it would be a mix of function, object and array!
Following terms might be worth to learn:
Yes, it's not a typo, right of the arrow is the return type!
Using a function type literal, we could type above search()
function, without interface, like this:
const search:
(text: string, pattern: string) => boolean =
function(text: string, pattern: string): boolean {
return text.search(pattern) >= 0;
}
Or even like that:
const search:
(text: string, pattern: string) => boolean =
(text: string, pattern: string): boolean => {
return text.search(pattern) >= 0;
}
Baffled? I think freedom of expression in context of computer languages undermines human common sense. Murphy's Law stands by: what can be misunderstood will be misunderstood! Just count the minutes you need to understand this code.
Here is a mix of object, function, and array, all in one interface.
The <JackOfAllTrades>
in line 13 is a cast-operator (mind that there are two kinds of casts in TS, the other one would be an as JackOfAllTrades
in line 15).
1 | interface JackOfAllTrades |
This is not only syntactically correct, but also all assertions are successful! Whether it is useful for everyday programming may be doubted.
ɔ⃝ Fritz Ritzberger, 2018-06-13