Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring Function type with TypeScript

I know I have asked this before, and I cannot find the question nor remember the answer.

I have an object with several methods with the same signature:

{

  foo: function(){
    return [];   // (return Array<T>)
  },

  bar: function(){
    return [];   // (return Array<T>)
  },

  baz: function(){
    return [];   // (return Array<T>)
  }

}

When I declare the interface for this object:

interface SomeObj {

   foo: Function,
   bar: Function,
   baz: Function

}

but I want to declare a type for these functions, something like this:

  type TestSuiteGetterFn <T>() => Array<T>;

  interface SomeObj {

       foo: TestSuiteGetterFn,
       bar: TestSuiteGetterFn,
       baz: TestSuiteGetterFn

    }

but this does not compile.

I have rarely found something so difficult to Google as this one.

like image 788
Alexander Mills Avatar asked Mar 05 '17 08:03

Alexander Mills


People also ask

How do you declare a return type for a function in TypeScript?

To define the return type for the function, we have to use the ':' symbol just after the parameter of the function and before the body of the function in TypeScript. The function body's return value should match with the function return type; otherwise, we will have a compile-time error in our code.

How do you create a function in TypeScript?

Writing a function in TypeScript is similar to writing them in JavaScript but with added parameters and return type. Note that any JavaScript function is a perfectly valid TypeScript function. However, we can do better by adding type.

How do you pass a function to a TypeScript function?

Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.


1 Answers

You simply forgot the equals sign when declaring your function type.

TypeScript Playground Permalink

type TestSuiteGetterFn<T> = () => Array<T>;

interface SomeObj {
     foo: TestSuiteGetterFn<string>,
     bar: TestSuiteGetterFn<number>,
     baz: TestSuiteGetterFn<string>
}
like image 69
gyre Avatar answered Oct 29 '22 03:10

gyre