typescript:具有属性的函数

时间:2015-07-21 13:50:06

标签: javascript angularjs typescript

我遇到以下代码问题:

CoreModule.filter('translateEnum', ['$parse', '$translate', function(
  $parse: angular.IParseService,
  $translate: angular.translate.ITranslateService
) {
  var translateFilter = function (translationId, namespace, interpolateParams, interpolation): string {
    if (!translationId) {
      return '';
    } else {
      if (!angular.isObject(interpolateParams)) {
        interpolateParams = $parse(interpolateParams)(this)
      }
      return $translate.instant( namespace + '.' + translationId, interpolateParams, interpolation)
    }
  }
  translateFilter.$stateful = true;
  return translateFilter;
}]);

我经常遇到编译错误:

>> app/modules/core/filters/filters.ts(47,19): error TS2339: Property '$stateful
' does not exist on type '(translationId: any, namespace: any, interpolateParams
: any, interpolation: any) => string'.

问题是我需要将$stateful: boolean属性赋予函数对象,而我不知道如何在打字稿中执行此操作。

以下是我做过的一些尝试,但都失败了:

interface StatefulFunction {
  (translationId, namespace, interpolateParams, interpolation): string;
  $stateful: boolean;
}

interface StatefulFunction {
  (...args: any[]): any;
  $stateful: boolean;
}

甚至

interface StatefulFunction extends Function {
  $stateful: boolean;
}

1 个答案:

答案 0 :(得分:1)

您可以这样做:

interface StatefulFunction {
    (): string;
    $stateful: boolean;
}

var translateFilter = <StatefulFunction>function (/*...*/) {
    /*...*/
};

改编自这个答案:https://stackoverflow.com/a/18640025/373655