最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Declaring Function type with TypeScript - Stack Overflow

programmeradmin5浏览0评论

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 pile.

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

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 pile.

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

Share Improve this question asked Mar 5, 2017 at 8:03 Alexander MillsAlexander Mills 100k165 gold badges532 silver badges909 bronze badges 4
  • 1 What error do you receive? – Chris Commented Mar 5, 2017 at 8:08
  • typescriptlang/play/… – Paul Samsotha Commented Mar 5, 2017 at 8:09
  • @peeskillet thanks, maybe that works, but I think gyre's answer is more ideal? – Alexander Mills 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. – Alexander Mills Commented Mar 5, 2017 at 9:14
Add a ment  | 

1 Answer 1

Reset to default 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>
}
发布评论

评论列表(0)

  1. 暂无评论