typescripttypescript-typestypescript-declarations

what typescript type would an anonymous function be?


thanks i'm learning to declare functions in .d.ts files

my javascript has

function generate(romeo) {
  return function(juliet) {
    return romeo + juliet 
  }
}

typescript declaration

  /**
   * Function that accepts strings and returns composed function.
   */
  export function generate(romeo: string): (juliet: string) => string;

object?


Solution

  • As VLAZ points out in the comments, the type Function exists, but it's not very useful: The point of TypeScript is to have certainty about the types that are returned, and Function does not indicate its parameters or return value.

    As in the docs on function type expressions, you can define a function type like this:

    type FunctionType = (param1: SomeParameter) => SomeReturnValue;
    

    For your case, that would look like this:

    /**
     * Function that accepts strings and returns composed function.
     */
    export function generate(romeo: string): (juliet: string) => string;
    

    You'll need to specify some kind of return value in order for TypeScript to recognize this as a function type, which could be any or unknown but ideally will be a more specific type like string above. (As usual, if the function is intended to not have a useful return value, then void is appropriate.) There is also a way to specify a Function that has additional properties, which is described in the docs as call signatures.