Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

  • found an object type about being non primitive
  • didn’t find any function type
  • What types would be legit?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading