我的TypeScript 1.5 + AngularJS 1项目中有以下过滤器:
module Filters{
export function percentage($filter:angular.IFilterService) {
return function(input: number, decimals: number): string{
return $filter('number')(input * 100, decimals) + '%';
}
}
var app = AppModule.getModule();
app.filter("percentage", Filters.percentage);
}
它假设将输入更改为百分比值 - 我知道,我可以采用不同的方式,但它不是关于过滤器本身 - 它是关于为过滤器分配类型。
使用以下代码,我在编译期间收到以下错误:
error TS2345: Argument of type 'number' is not assignable to parameter of type '{}[]'.
Property 'length' is missing in type 'Number'.
在说明书中指出了这一点:
interface IFilterService {
/**
* Usage:
* $filter(name);
*
* @param name Name of the filter function to retrieve
*/
(name: string): IFilterFunc;
}
interface IFilterFunc {
<T>(array: T[], expression: string | IFilterPatternObject | IFilterPredicateFunc<T>, comparator?: IFilterComparatorFunc<T>|boolean): T[];
}
但是,我不确定是什么问题。有任何想法吗?
答案 0 :(得分:2)
不知道您使用的是什么版本的打字,但过滤器类型的定义已经更新,因为最新的1.4+类型。
所以definition for filter专门处理你在重载的帮助下传递的过滤器类型,它看起来像这样:
interface IFilterService {
(name: 'filter'): IFilterFilter;
(name: 'currency'): IFilterCurrency;
(name: 'number'): IFilterNumber;
(name: 'date'): IFilterDate;
(name: 'json'): IFilterJson;
(name: 'lowercase'): IFilterLowercase;
(name: 'uppercase'): IFilterUppercase;
(name: 'limitTo'): IFilterLimitTo;
(name: 'orderBy'): IFilterOrderBy;
/**
* Usage:
* $filter(name);
*
* @param name Name of the filter function to retrieve
*/
<T>(name: string): T;
}
interface IFilterNumber {
/**
* Formats a number as text.
* @param number Number to format.
* @param fractionSize Number of decimal places to round the number to. If this is not provided then the fraction size is computed from the current locale's number formatting pattern. In the case of the default locale, it will be 3.
* @return Number rounded to decimalPlaces and places a “,” after each third digit.
*/
(value: number|string, fractionSize?: number|string): string;
}
更新angular.d.ts应解决您的问题。看起来您的版本有错误的过滤器类型fixed during this merge。