13

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.

4
  • 1
    What error do you receive? Commented Mar 5, 2017 at 8:08
  • typescriptlang.org/play/… Commented Mar 5, 2017 at 8:09
  • @peeskillet thanks, maybe that works, but I think gyre's answer is more ideal? Commented Mar 5, 2017 at 8:15
  • @Chris I got a red squiggly in my IDE (Webstorm), I didn't need to transpile to know there would be an error, but doubt it would be a meaningful error. Commented Mar 5, 2017 at 9:14

1 Answer 1

13

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>
}
Sign up to request clarification or add additional context in comments.

4 Comments

Glad to help! Learned something new about TypeScript myself, too.
ditto if you think it's a well framed question
Guys what is that <T> ?
<T> is the generic type, it must be passed in, see the 3 times it is passed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.