Alexander Mills
Alexander Mills

Reputation: 100020

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.

Upvotes: 13

Views: 14384

Answers (1)

gyre
gyre

Reputation: 16777

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>
}

Upvotes: 13

Related Questions