Home > OS >  Typescript describable function implementation
Typescript describable function implementation

Time:07-07

I am working through the Typescript specification and I am unable to create a workable implementation for describable functions.

https://www.typescriptlang.org/docs/handbook/2/functions.html

The example is incomplete and doesnt show the code required for execution and implementation of the function signature. Function doSomething executes fn() but the example doesnt show it being called to detail the values being passed in. What would a call to doSomething look like? What would the signature of an instance of DescribableFunction look like?

type DescribableFunction = {
  description: string;
  (someArg: number): boolean;
};
function doSomething(fn: DescribableFunction) {
  console.log(fn.description   " returned "   fn(6));
}
// TBD: call doSomething and pass in an instance of DescribableFunction with implementation of the signature (someArg: number): boolean.

CodePudding user response:

It is just a case of supplying a function which matches the type declaration

function IsNegative (someArg: number) : boolean {return someArg<0 };
IsNegative.description = "returns true if the input is negative";
doSomething(IsNegative)

Output

returns true if the input is negative returned false

Playground link

  • Related