0

Working on a graph visualization task, I found the following interface in the d3.js typings (upstream link here):

export interface Force<NodeDatum extends SimulationNodeDatum, LinkDatum extends SimulationLinkDatum<NodeDatum> | undefined> {
    (alpha: number): void; // <- ???
    initialize?(nodes: NodeDatum[]): void;
}

This (alpha: number): void; seems to me a little bit uncommon. My intuition from different OOP languages says as if it would be some like a C++ functor. But I couldn't find the correct syntax to implement it.

What is it?

How can I implement this interface?

How can I call this method?

peterh
  • 11,875
  • 18
  • 85
  • 108

1 Answers1

1

From the Typescript docs :

Function Types Interfaces are capable of describing the wide range of shapes that JavaScript objects can take. In addition to describing an object with properties, interfaces are also capable of describing function types.

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. Each parameter in the parameter list requires both name and type.

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

Once defined, we can use this function type interface like we would other interfaces. Here, we show how you can create a variable of a function type and assign it a function value of the same type.

let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
    let result = source.search(subString);
    return result > -1;
}

So you can implement it with

let test: Force = function(alpha: number) {
   //do stuff
}
//optional part
test.initialize = function(nodes: NodeDatum[]) {
   //do other stuff
}
peterh
  • 11,875
  • 18
  • 85
  • 108
n00dl3
  • 21,213
  • 7
  • 66
  • 76